|
|
@ -10,7 +10,7 @@ namespace {yourApp}\behaviors; |
|
|
|
|
|
|
|
use yii\base\Behavior; |
|
|
|
use yii\db\ActiveRecord; |
|
|
|
use yii\db\Expression; |
|
|
|
use yii\helpers\ArrayHelper; |
|
|
|
|
|
|
|
class BitFlagBehavior extends Behavior |
|
|
|
{ |
|
|
@ -28,12 +28,32 @@ class BitFlagBehavior extends Behavior |
|
|
|
public function events() |
|
|
|
{ |
|
|
|
return [ |
|
|
|
ActiveRecord::EVENT_INIT => 'eventInit', |
|
|
|
ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave', |
|
|
|
ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate', |
|
|
|
ActiveRecord::EVENT_AFTER_FIND => 'afterFind', |
|
|
|
ActiveRecord::EVENT_AFTER_REFRESH => 'afterFind', |
|
|
|
]; |
|
|
|
} |
|
|
|
|
|
|
|
public function eventInit() |
|
|
|
{ |
|
|
|
$this->addFlagFieldsToOwner(); |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* 添加自定义标志属性 |
|
|
|
*/ |
|
|
|
public function addFlagFieldsToOwner() |
|
|
|
{ |
|
|
|
$owner = $this->owner; |
|
|
|
$fields = []; |
|
|
|
foreach ($owner::BIT_FLAGS as $bigFlag) { |
|
|
|
$fields = ArrayHelper::merge($fields, array_combine($bigFlag, $bigFlag)); |
|
|
|
} |
|
|
|
$owner->_fields = $fields; |
|
|
|
} |
|
|
|
|
|
|
|
public function beforeSave() |
|
|
|
{ |
|
|
|
foreach ($this->bitFlags as $bitFlag => $flags) { |
|
|
@ -139,7 +159,15 @@ class MyModel extends base\MyModel |
|
|
|
// ] |
|
|
|
]; |
|
|
|
|
|
|
|
// 其他Model代码...... |
|
|
|
/** |
|
|
|
* @var string[] 自定义标志字段 |
|
|
|
*/ |
|
|
|
public $_fields; |
|
|
|
|
|
|
|
public function fields() |
|
|
|
{ |
|
|
|
return ArrayHelper::merge(parent::fields(), $this->_fields); |
|
|
|
} |
|
|
|
|
|
|
|
public function behaviors() |
|
|
|
{ |
|
|
@ -162,6 +190,8 @@ class MyModel extends base\MyModel |
|
|
|
$config = ['bitFlags' => self::BIT_FLAGS]; |
|
|
|
return new MyModelQuery(get_called_class(), $config); |
|
|
|
} |
|
|
|
|
|
|
|
// 其他Model代码...... |
|
|
|
} |
|
|
|
``` |
|
|
|
|
|
|
|