> 有時候查詢某條數據時候,需要用到的條件很多,很繁瑣時,建議將這些條件封裝起來,供activequery使用。
> 我們這里就拿“訂單表”來舉例。比如訂單狀態“待支付”、‘可消費’、“已支付”等等各種條件。而且這些狀態條件在很多地方都會同時用到,所以就可以考慮進行封裝了。
[TOC]
#### 1. 創建OrderQuery
~~~
namespace common\models;
class OrderQuery extends ActiveQuery
{
//可消費狀態篩選
public function queryCanConsumeStatus()
{
return $this->andWhere(['or',
['status' => 1],
['status' => 3],
['status' => 6],
]);
}
//已支付狀態篩選
public function queryPayedStatus()
{
return $this->andWhere(['status' => 8]);
}
//待支付狀態篩選
public function queryUnpayedStatus()
{
return $this->andWhere(['status' => 2]);
}
}
~~~
#### 2. Order Model中使其支持OrderQuery
~~~
class Order extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'order';
}
public static function find()
{
return new OrderQuery(get_called_class());
}
}
~~~
#### 3. Controller中使用示例
~~~
$list = Order::find()->where(['customer_id'=>$customerId])->queryCanConsumeStatus()->list();
var_dump($list);
~~~
- 基礎教程
- 入門安裝
- Yii2 composer 安裝慢解決
- Cookies
- 數據庫操作
- 數據提供者
- 助手類
- 驗證規則
- GridView
- DetailView
- YII2分頁
- JS、CSS的引用
- Excel導出
- 中文轉拼音
- 發送郵件
- 第三方插件
- Session跨域共享
- Url跨域訪問
- 場景應用
- 查詢條件鏈
- Session分布式共享
- Redis的使用
- mongodb
- 高級教程
- 自定義gii模板
- 角色權限管理(RBAC)
- user組件的配置
- 國際化(I18N)
- 小部件(Widget)
- 模塊(Module)
- 行為(Behavior)
- 緩存(Cache)
- migrate 數據庫遷移
- phpstorm
- 快捷鍵
- 自定義
- 其它插件