gpt4 book ai didi

php - Yii2:在 ActiveRecord 的 with() 中使用 realtion 的范围

转载 作者:可可西里 更新时间:2023-11-01 13:24:17 24 4
gpt4 key购买 nike

在 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();

最佳答案

一个干净的解决方案是覆盖模型的 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 的更多示例。构建命名作用域的类:

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

关于php - Yii2:在 ActiveRecord 的 with() 中使用 realtion 的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25369616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com