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

Yii2 : ActiveQuery Example and what is the reason to generate ActiveQuery class separately in Gii?(Yii2 : ActiveQuery Example 以及在 Gii 中单独生成 ActiveQuery 类的原因是什么?)
本文介绍了Yii2 : ActiveQuery Example 以及在 Gii 中单独生成 ActiveQuery 类的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Could you provide an example usage. Description will be highly appreciated. I can not find a good example for it.

推荐答案

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

The Active Query represents a DB query associated with an Active Record class. It is usually used to override the default find() method of a specific model where it will be used to generate the query before sending to 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 Yii2 中的命名范围.您所要做的就是覆盖 model 类中的 find() 方法以使用上面的 ActiveQuery 类:

If you worked before with Yii 1 then this is what replaces Yii 1.x Named Scopes in Yii2. All you have to do is to override the find() method in your model class to use the ActiveQuery class above :

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

那么你可以这样使用它:

Then you can use it this way :

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

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

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

<小时>

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


A different use case of the same ActiveQuery class defined above is by using it when defining relational data in a related model class like:

class Customer extends yiidbActiveRecord
{
    ...

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

然后您可以通过执行以下操作来急切地加载客户与他们各自的已付款订单:

Then you can eager load customers with their respective payed orders by doing :

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

这篇关于Yii2 : ActiveQuery Example 以及在 Gii 中单独生成 ActiveQuery 类的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)