PHP yii 2, is there a way to prefetch a related model with a condition

时间:2016-10-20 12:42:32

标签: php yii2

PriceAlert::find()->andWhere(['user_id' => Yii::$app->user->id])->orderBy('complete DESC, updated_at DESC')->with('product')

So i have recently discovered the "with" feature for Yii queries, as you can see in the query above, i'm fetching my price alerts with their related products, which saves me from having to loop through each price alert and fetching each product individually, but my question is there a way to force a condition on this, what i want is to get the price alerts with a condition on the products, so i only want to get the price alerts where a condition on their related products is true.

2 个答案:

答案 0 :(得分:2)

You can do it in with method and closure.

...->with(['product' => function ($query) {
    $query->andWhere(/* product conditions here */);
}]);

See docs.

答案 1 :(得分:2)

Previous answer is incomplete, if you want to add a condition on products in the main query (not the one who will fetch the related records), you should simply use joinWith() instead of with(), e.g. :

PriceAlert::find()
    ->joinWith('product')
    ->andWhere(['user_id' => Yii::$app->user->id])
    ->andWhere(['>', 'product.price', 100])
    ->orderBy('complete DESC, updated_at DESC')
    ->all();

Or if you want to specify some extra conditions in the ON part of the JOIN query :

PriceAlert::find()
    ->joinWith(['product' => function ($q) {
        // add conditions here
    }])
    ->andWhere(['user_id' => Yii::$app->user->id])
    ->orderBy('complete DESC, updated_at DESC')
    ->all();

Read more about Joining with Relations.