是否可以按关联分组结果集?
我有以下协会
AgthemesTable
$this->belongsTo('Sites');
$this->hasMany('Agthemelanguages');
AgthemeLanguagesTable
$this->belongsTo('Languages');
由于我想为每个Agthemes
获取所有Agthemelanguages
,我写了以下查询:
$agThemes = $this->Agthemes->find('all')
->select(['id', 'name', 'approved', 'published'])
->contain ([
'Sites' => function ($q) {
return $q->select(['id'])
->autoFields(false);
},
'Agthemelanguages.Languages' => function ($q) use ($localized_name) {
return $q->select(
[
'id',
'code',
'code3',
$localized_name
]
);
}
]
)
->where([
'approved' => true,
'published' => true
])
->matching(
'Sites', function ($q) use($site_id) {
return $q->where([
'Sites.id' => $site_id
]);
}
)
->group('language_id')
->all();
但我收到错误:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'language_id' in 'group statement'
实际上,生成的sql查询中没有AgthemeLanguages
:
SELECT Agthemes.id AS `Agthemes__id`, Agthemes.name AS `Agthemes__name`, Agthemes.approved AS `Agthemes__approved`, Agthemes.published AS `Agthemes__published` FROM agthemes Agthemes INNER JOIN sites Sites ON (Sites.id = :c0 AND Sites.id = (Agthemes.site_id)) WHERE (approved = :c1 AND published = :c2) GROUP BY language_id
如果没有group
语句,我会得到多种结果:
'items' => [
(int) 0 => object(App\Model\Entity\Agtheme) {
'id' => (int) 40,
'name' => '...',
'approved' => (int) 1,
'published' => (int) 1,
'agthemelanguages' => [
(int) 0 => object(App\Model\Entity\Agthemelanguage) {
'id' => (int) 372,
'agtheme_id' => (int) 40,
'language_id' => (int) 1,
'name' => '....',
'comment' => '....',
'language' => object(App\Model\Entity\Language) {
'id' => (int) 1,
...
},
...,
],
...,
},
...
]
如何定义此类查询? 人
修改
我终于得到了我希望编写的查询,但它需要首先创建另一个查询以了解所有可用的Agthemes
并将其ID放在$agThemeIds
数组中:
$agThemeLanguages = $this->Languages->find('all')
->select(
[
'id',
'code',
'code3',
$localized_name
]
)
->contain ([
'Agthemelanguages' => function ($q) use ($agThemeIds) {
return $q->where(['agtheme_id IN ' => $agThemeIds]);
}
]
)
->matching('Agthemelanguages', function ($q) use ($agThemeIds) {
return $q->where(['agtheme_id IN ' => $agThemeIds]);
})
->group(['Languages.id'])
->all();