Yii2: use realtion regions in () ActiveRecord

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 the scope of a relation in the with () callback function in Yii2?

 Customer::find()->with([ 'orders' => function ($query) { $query->andWhere('status = 1'); }, 'country', ])->all(); 
+6
source share
1 answer

The pure solution is to override the find() model method to use the 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 associate many of them, for example, with Yii 1 scopes. In this post you will find more examples of how to use the ActiveQuery class to create Named Scopes :

Yii2: an example of ActiveQuery and what is the reason for generating the ActiveQuery class separately in Gii?

+3
source

Source: https://habr.com/ru/post/973997/


All Articles