答案 0 :(得分:79)
Active Query表示与Active Record类关联的数据库查询。它通常用于覆盖特定模型的默认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,那么这就取代了Yii2中的Yii 1.x Named Scopes。您所要做的就是覆盖模型类中的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();