代码之家  ›  专栏  ›  技术社区  ›  GreyRoofPigeon

深度联想和

  •  1
  • GreyRoofPigeon  · 技术社区  · 7 年前

    考虑以下模型:

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

    有什么想法吗?

    0 回复  |  直到 7 年前