Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: Use scopes of realtion in with() of 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 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();
like image 433
EvilKarter Avatar asked Aug 18 '14 18:08

EvilKarter


1 Answers

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?

like image 126
Salem Ouerdani Avatar answered Oct 21 '22 13:10

Salem Ouerdani