我在 Laravel 项目中有一个范围查询,它隐式地获取了我不希望出现在结果集中的两列,因为它们会导致 ONLY_FULL_GROUP_BY 错误,我不想禁用此数据库条件。
我们有如下关系:
组织有 -> 类别
public function categories()
{
return $this->belongsToMany(
Category::class,
'organisation_unit_template_categories',
'organisation_unit_id',
'template_category_id'
);
}
类别有 -> 模板
public function templates()
{
return $this->hasMany(Template::class);
}
模板有 -> 维度
public function dimensions()
{
return $this->belongsTo(Dimensions::class, 'dimensions_id');
}
我们的类别也有一个范围查询,这样我们就可以得到至少包含一个模板的所有类别,该模板的维度为'digital = 0'
public function scopeIsPrint($query)
{
return $query
->select($this->getTable().'.*')
->join('templates', 'template_categories.id', '=', 'templates.category_id')
->join('template_dimensions', 'template_dimensions.id', '=', 'templates.dimensions_id')
->where('template_dimensions.digital', 0)
->groupBy($this->getTable().'.id');
}
我们像这样从 Controller 调用范围查询:
$categories = $this->organisation->categories()->isPrint()->get();
这是输出:
SELECT
`template_categories`.*,
`organisation_unit_template_categories`.`organisation_unit_id` AS `pivot_organisation_unit_id`,
`organisation_unit_template_categories`.`template_category_id` AS `pivot_template_category_id`
FROM
`template_categories`
INNER JOIN
`organisation_unit_template_categories` ON `template_categories`.`id` = `organisation_unit_template_categories`.`template_category_id`
INNER JOIN
`templates` ON `template_categories`.`id` = `templates`.`category_id`
INNER JOIN
`template_dimensions` ON `template_dimensions`.`id` = `templates`.`dimensions_id`
WHERE
`organisation_unit_template_categories`.`organisation_unit_id` = 2
AND `template_dimensions`.`digital` = 0
AND `template_categories`.`deleted_at` IS NULL
GROUP BY `template_categories`.`id`
我怎样才能确保这两列:
`organisation_unit_template_categories`.`organisation_unit_id` AS `pivot_organisation_unit_id`,
`organisation_unit_template_categories`.`template_category_id` AS `pivot_template_category_id`
不包含在查询中,让我知道为什么首先隐式添加它们的加分点。
非常感谢
最佳答案
Our categories also have a scope query, so that we can get all categories which contain at least one template who's dimensions have 'digital = 0'
我的建议是重写查询以使用 exists
而不是 join
和 group by
。
public function scopeIsPrint($query)
{
return $query
->whereExists(function($q) {
return $q->selectRaw('1')->from('templates')
->join('template_dimensions', 'template_dimensions.id', '=', 'templates.dimensions_id')
->whereRaw('template_categories.id=templates.category_id')
->where('template_dimensions.digital', 0)
})
}
关于php - 从 Laravel 范围查询中排除连接列 ONLY_FULL_GROUP_BY 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57094697/