CakePHP深度关联之和

时间:2018-10-19 17:58:21

标签: php cakephp cakephp-3.x

请考虑以下模型:

/* 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 feedingsfeedings 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])

有什么想法吗?

0 个答案:

没有答案