moontensai / yii2-before-query

在Yii 2模型中添加查询前或查找前事件

dev-master / 1.0.x-dev 2015-06-29 05:14 UTC

This package is not auto-updated.

Last update: 2024-09-14 17:31:57 UTC


README

在Yii 2模型中添加查询前事件

安装

安装此扩展的首选方式是通过 Composer

运行以下命令

$ composer require mootensai/yii2-before-query "dev-master"

或者在您的 composer.json 文件的 require 部分添加以下内容:

"mootensai/yii2-before-query": "dev-master"

  1. 基础Trait Before Query
namespace common\traits\base;
trait BeforeQueryTrait{

    public static function find() {
        $obj = new static;
        $class = new \ReflectionClass($obj);
        $condition = [];
        foreach ($class->getProperties(\ReflectionProperty::IS_STATIC) as $property) {
            if(strpos($property->getName(),'BEFORE_QUERY') !== false && is_array($property->getValue($obj))){
                $condition = array_merge($condition, $property->getValue($obj));
            }
        }
        return parent::find()->andFilterWhere($condition);
    }
}
  1. 在模型上添加新属性

然后,您可以在模型上添加新的属性,例如

class MyClass extends \yii\db\ActiveRecord{
    use \common\traits\base\BeforeQueryTrait;
    public static $BEFORE_QUERY = ['myColumn' => 'myValue'];
}

注意:您可以在以下位置学习 public static $BEFORE_QUERY 的内容

https://yiiframework.cn/doc-2.0/yii-db-queryinterface.html#where%28%29-detail

  1. 您可以创建一个新的Trait。

例如,我创建了一个软删除布尔Trait

trait SoftDeleteBoolTrait{
    public static $BEFORE_QUERY_SOFT_DELETE = ['isdeleted' => 0];
    
    public function deleteSoft() {
        $col = key(static::$BEFORE_QUERY_SOFT_DELETE);
        $this->{$col} = 1;
        return $this->save(false,[$col]);
    }
    
    public static function restore($id) {
        $col = key(static::$BEFORE_QUERY_SOFT_DELETE);
        $model = parent::findOne($id, 1);
        $model->{$col} = 0;
        $model->save(false,[$col]);
    }
}

在模型中使用它

class MyClass extends \yii\db\ActiveRecord{
    use \mootensai\beforequery\base\BeforeQueryTrait;
    use \mootensai\beforequery\traits\SoftDeleteBoolTrait;
}