user2968505 user2968505 - 6 months ago 37
PHP Question

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

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.


You can do it in with method and closure.

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

See docs.