请考虑以下模型:
/* HerdsTable.php */
class HerdsTable extends Table
{
public function initialize(array $config)
{
...
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->hasMany('Costs', [
'foreignKey' => 'herd_id'
]);
$this->hasMany('Feedings', [
'foreignKey' => 'herd_id'
]);
/* FeedingsTable.php */
class FeedingsTable extends Table
{
public function initialize(array $config)
{
...
$this->belongsTo('Herds', [
'foreignKey' => 'herd_id',
'joinType' => 'INNER'
]);
$this->hasMany('Feedingssupps', [
'foreignKey' => 'feeding_id'
]);
}
/* FeedingssuppsTable.php */
class FeedingssuppsTable extends Table
{
public function initialize(array $config)
{
...
$this->belongsTo('Feedings', [
'foreignKey' => 'feeding_id',
'joinType' => 'INNER'
]);
}
所以herd has many feedings
和feedings has many feedingssupps
feedingssupps
包含以下列:id, feeding_id, name, weight, dryweight, price
。
在牧群控制器中,我想获得weight, dryweight, price
的总和,并按name
分组。但是我无法弄清楚。
这是我想出的:
$herd = $this->Herds->find()
->contain(
[
'Costs',
'Feedings' =>
['Feedingssupps' => function ($q) use ($id)
{
return $q
->select(['Feedingssupps.feeding_id', 'total' => 'SUM(Feedingssupps.price)'])
->group('Feedingssupps.name');
}]
])
->where(['Herds.id'=> $id])
有什么想法吗?