In Yii1 I could do something like this:
$posts=Post::model()->with(array(
'comments'=>array(
'scopes'=>array('recently','approved')
),
))->findAll();
Is there a way to call a scope of a relation in the callback function of with() in Yii2?
Customer::find()->with([
'orders' => function ($query) {
$query->andWhere('status = 1');
},
'country',
])->all();
A clean solution is by overriding the model's find()
method to use a custom ActiveQuery class :
class Order extends yii\db\ActiveRecord
{
public static function find()
{
return new OrderQuery(get_called_class());
}
}
class OrderQuery extends yii\db\ActiveQuery
{
public function payed()
{
return $this->andWhere(['status' => 1]);
}
}
then you can use it like :
$customers = Customer::find()->with([
'orders' => function($q) {
$q->payed();
}
])->all();
You can also chain many of them like Yii 1 scopes. In this post you'll find more examples on how to use ActiveQuery class to build Named Scopes :
Yii2 : ActiveQuery Example and what is the reason to generate ActiveQuery class separately in Gii?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With