This function is very similar to BelongsToMany::_buildQuery().