Yii2 - left join on multiple condition

后端 未结 3 2051
醉话见心
醉话见心 2021-01-12 14:25

I have three tables with the following relations,

  ------- 1        0..* ------------
 |Product|-------------|Availability|
  -------               --------         


        
3条回答
  •  难免孤独
    2021-01-12 14:50

    I believe this one is better solution. Instead of using Raw queries like leftJoin you should complement your joinWith relations with andOnCondition (which adds needed where conditions into your join statement).

    $products = Product::find()
        ->joinWith(['metaData' => function (ActiveQuery $query) {
            return $query
                ->andWhere(['=', 'meta_data.published_state', 1]);
        }])
        ->joinWith(['availability' => function (ActiveQuery $query) {
            return $query
                ->andOnCondition(['>=', 'availability.start', strtotime('+7 days')])
                ->andWhere(['IS', 'availability.ID', NULL]);
        }])
        ->all();
    

    In addition it looks cleaner when you write where clauses inside relations. It works the same as writing it outside (if I'm not wrong), but when refactoring your query, you can easily delete the whole relation without forgetting relation conditions outside.

提交回复
热议问题