Рассмотрим следующие модели:
/* 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])
Есть мысли?