php - Yii2: Use scopes of realtion in with() of ActiveRecord -
in yii1 this:
$posts=post::model()->with(array( 'comments'=>array( 'scopes'=>array('recently','approved') ), ))->findall(); is there way call scope of relation in callback function of with() in yii2?
customer::find()->with([ 'orders' => function ($query) { $query->andwhere('status = 1'); }, 'country', ])->all();
a clean solution overriding model's find() method use 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 can use :
$customers = customer::find()->with([ 'orders' => function($q) { $q->payed(); } ])->all(); you can chain many of them yii 1 scopes. in post you'll find more examples on how use activequery class build named scopes :
yii2 : activequery example , reason generate activequery class separately in gii?
Comments
Post a Comment