ActiveRecord where and order on via-table

前端 未结 8 736
南旧
南旧 2020-12-16 12:22

I have three database table:

product (id, name)

product_has_adv (product,advantage,sort,important)

advantage (id, text)

In ProductModel I def

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 13:15

    As explained by @arogachev, the viaTable uses two separate queries, which renders any intermediate orderBy obsolete

    You could replace the viaTable with an innerJoin as follows, in a similar solution to @MartinM

    public function getAdvantages()
    {
       return $this->hasMany(AdvantageModel::class, ['pha.product' => 'id'])
           ->innerJoin('product_has_advantage pha', 'pha.advantage = advantage.id')
           ->andWhere(['pha.important' => 1])
           ->orderBy(['pha.sort' => SORT_ASC]);
    }
    

    By adjusting the result of hasMany, you are adjusting the query for the target class - AdvantageModel::find(); product_has_advantage can be joined via the advantage identity

    The second parameter of hasMany, link, can be viewed as [ query.column => $this->attribute ], which you can now support via the joined product_has_advantage and its product identity


    Note, when using viaTable, the link parameter can be viewed as if the intermediate query is complete and we are starting from there; [ query.column => viaTable.column ] hence ['id', 'advantage'] in your question

提交回复
热议问题