【问题标题】:Yii2: Use scopes of realtion in with() of ActiveRecordYii2:在 ActiveRecord 的 with() 中使用 realtion 范围
【发布时间】:2014-10-11 17:44:09
【问题描述】:

在 Yii1 中我可以这样做:

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

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

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

【问题讨论】:

    标签: php activerecord scope yii2


    【解决方案1】:

    一个干净的解决方案是覆盖模型的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]);
        }
    }
    

    然后你可以像这样使用它:

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

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

    Yii2 : ActiveQuery Example and what is the reason to generate ActiveQuery class separately in Gii?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多