gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:06:47 24 4
gpt4 key购买 nike

您能否提供一个示例用法。描述将不胜感激。我找不到一个很好的例子。

ActiveQuery in Gii

最佳答案

Active Query表示与 Active Record 关联的数据库查询类(class)。它通常用于覆盖特定模型的默认 find() 方法,用于在发送到 DB 之前生成查询:

class OrderQuery extends ActiveQuery
{
public function payed()
{
return $this->andWhere(['status' => 1]);
}

public function big($threshold = 100)
{
return $this->andWhere(['>', 'subtotal', $threshold]);
}

}

如果你之前使用过 Yii 1 那么这就是替换 Yii 1.x Named Scopes 的东西在 Yii2 中。您所要做的就是覆盖 model 类中的 find() 方法以使用上面的 ActiveQuery 类:

// This will be auto generated by gii if 'Generate ActiveQuery' is selected
public static function find()
{
return new \app\models\OrderQuery(get_called_class());
}

然后你可以这样使用它:

$payed_orders      =   Order::find()->payed()->all();

$very_big_orders = Order::find()->big(999)->all();

$big_payed_orders = Order::find()->big()->payed()->all();

上面定义的相同 ActiveQuery 类的不同用例是在相关模型 类中定义关系数据 时使用它,例如:

class Customer extends \yii\db\ActiveRecord
{
...

public function getPayedOrders()
{
return $this->hasMany(Order::className(),['customer_id' => 'id'])->payed();
}
}

然后您可以通过以下方式为客户加载他们各自的已付款订单:

$customers = Customer::find()->with('payedOrders')->all(); 

关于php - Yii2 : ActiveQuery Example and what is the reason to generate ActiveQuery class separately in Gii?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31948917/

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