Yii2: ActiveQuery “with” not working

后端 未结 2 1472
挽巷
挽巷 2020-12-20 21:57

Circumstances

I have three models/db-tables related with 1:n each: An order has multiple commissions and a commission has multiple

相关标签:
2条回答
  • 2020-12-20 22:40

    Found the soution myself. The naming changes between Yii1 and Yii2 lead to a little confusion. To prevent others from wasting time here the details:

    Yii1

    In yii 1 you would join in a relation (exemplary: commission) directly like this:

    $query->with = 'commission'
    $query->together = true;
    

    Yii2 / difference

    When calling the with-method like showed in the question the relation was successfully added to the with-array of the ActiveQuery. However, when executing the query, the join part was missing.

    Solution

    Seems like the with-method is NOT the way to go. Instead I used the method called joinWith with the following signature:

    public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
    

    Now as described in the answer I defined the relation as the first argument ('commission.order') and left the rest as is, because the default values are perfectly fine. Pay attention to the default value of the second parameter. this makes sure the relations are joined in directly!

    Voilà...the resulting sql contains the needed joins. One pitfall is to be considered though: Ambigious column namings is of course to be handled by ourselves! Link to the documentation of the method:

    http://www.yiiframework.com/doc-2.0/yii-db-activequery.html#joinWith()-detail

    0 讨论(0)
  • If you want a JOIN use:

    $this->joinWith(['commission.order']);
    
    0 讨论(0)
提交回复
热议问题