Yii2:在ActiveRecord的with()中使用实现范围

Evi*_*ter 6 php activerecord scope yii2

在Yii1中,我可以这样做:

$posts=Post::model()->with(array(
    'comments'=>array(
        'scopes'=>array('recently','approved')
    ),
))->findAll();
Run Code Online (Sandbox Code Playgroud)

有没有办法在Yii2中的with()的回调函数中调用关系的范围?

Customer::find()->with([
    'orders' => function ($query) {
        $query->andWhere('status = 1');
    },
    'country',
])->all();
Run Code Online (Sandbox Code Playgroud)

Sal*_*ani 5

一个干净的解决方案是覆盖模型的find()方法以使用自定义ActiveQuery类:

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]);
    }
}
Run Code Online (Sandbox Code Playgroud)

那么你可以像这样使用它:

$customers = Customer::find()->with([
    'orders' => function($q) {
        $q->payed();
    }
])->all();
Run Code Online (Sandbox Code Playgroud)

您还可以像 Yii 1 范围一样链接其中许多。在这篇文章中,您将找到更多关于如何使用ActiveQuery类构建命名作用域的示例:

Yii2 : ActiveQuery Example 以及在 Gii 中单独生成 ActiveQuery 类的原因是什么?