mdmsoft / yii2-ar-behaviors
为 Yii2 的行为
1.3
2016-02-22 02:51 UTC
Requires
- yiisoft/yii2: ~2.0
This package is not auto-updated.
Last update: 2024-09-14 16:03:16 UTC
README
安装
安装此扩展的首选方式是通过 composer。
运行以下命令之一
php composer.phar require mdmsoft/yii2-ar-behaviors "~1.0"
或将以下内容添加到您的 composer.json
文件的 require 部分中。
"mdmsoft/yii2-ar-behaviors": "~1.0"
查询范围
QueryScopeBehavior
将通过 Yii::$container
自动附加到 ActiveQuery
。您可以使用此行为从 ActiveRecord
创建查询范围。
class Sales extends ActiveRecord { ... public static function defaultScope($query) { $query->andWhere(['status' => self::STATUS_OPEN]); } public static function bigOrder($query, $ammount=100) { $query->andWhere(['>','ammount',$ammount]); } } ---- // get all opened sales Sales::find()->all(); // apply defaultScope // opened sales and order bigger than 200 Sales::find()->bigOrder(200)->all();
扩展行为
不通过继承扩展 Activerecord
😀。此行为用于合并两个表并将其作为单个 ActiveRecord 处理。
示例:我们有一个模型 CustomerDetail
/** * @property integer $id * @property string $full_name * @property string $organisation * @property string $address1 * @property string $address2 */ class CustomerDetail extends ActiveRecord { }
和模型 Customer
/** * @property integer $id * @property string $name * @property string $email */ class Customer extends ActiveRecord { public function behaviors() { return [ [ 'class' => 'mdm\behaviors\ar\ExtendedBehavior', 'relationClass' => CustomerDetail::className(), 'relationKey' => ['id' => 'id'], ], ]; } }
之后,我们可以从 Customer
访问 CustomerDetail
属性,就像它们自己的属性一样
$model = new Customer(); $model-name = 'Doflamingo'; $model->organisation = 'Donquixote Family'; $model->address = 'North Blue'; $model->save(); // it will save this model and related model
关系行为
用于保存模型及其关系。
class Order extends ActiveRecord { public function getItems() { return $this->hasMany(Item::className(),['order_id'=>'id']); } public function behaviors() { return [ [ 'class' => 'mdm\behaviors\ar\RelationBehavior', 'beforeRSave' => function($item){ return $item->qty != 0; } ], ]; } }
用法
$model = new Order(); if($model->load(Yii::$app->request->post()){ $model->items = Yii::$app->request->post('Item',[]); $model->save(); }
关系特质
类似于关系行为
class Order extends ActiveRecord { use \mdm\behavior\ar\RelationTrait; public function getItems() { return $this->hasMany(Item::className(),['order_id'=>'id']); } public function setItems($value) { $this->loadRelated('items', $value); } public function beforeRSave($item) { return $item->qty != 0; } }
用法
$model = new Order(); if($model->load(Yii::$app->request->post()){ $model->items = Yii::$app->request->post('Item',[]); $model->save(); }