6

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();
lin
  • 16,787
  • 4
  • 49
  • 79
EvilKarter
  • 257
  • 7
  • 21

1 Answers1

5

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?

Community
  • 1
  • 1
Salem Ouerdani
  • 6,956
  • 2
  • 37
  • 47