Yii2一些方法技巧集合

程序人生

表单验证

  • 表单验证,两个参数中至少需要一个
    public function rules()
    {
        return [
            [['card_id', 'card_code'], 
            function ($attribute, $param) {
                //两个参数中至少需要一个
                if (empty($this->card_code) && empty($this->card_id)) {
                    $this->addError($attribute, 'card_id/card_code至少要填一个');
                }
            }, 
            'skipOnEmpty' => false],
        ];
    }
  • 表单验证,去除首尾空格
    public function rules()
    {
        return [[title', 'content'],'trim']];
    }
  • 校验 user_id 在User表中是否存在,并自定义错误信息
    public function rules()
    {
        return [
            ...
            [['user_id'], 'exist',
                'targetClass' => User::className(),
                'targetAttribute' => 'id',
                'message' => '此{attribute}不存在。'
            ],
            ...
        ];
    }
  • Model 里面 rules 联合唯一规则
    [['store_id', 'member_name'], 'unique', 'targetAttribute' => ['store_id', 'member_name'], 'message' => 'Store ID 和 Member Name 的组合已经被使用了.'],
  • 表单提交失败获取save()错误信息调试代码
    echo array_values($model->getFirstErrors())[0];exit;
    var_dump($model->getErrors());die;
  • 单独为某个Action关闭 Csrf 验证

    新建一个Behavior

    use Yii;
    use yii\base\Behavior;
    use yii\web\Controller;
    
    class NoCsrf extends Behavior
    {
        public $actions = [];
        public $controller;
        public function events()
        {
            return [Controller::EVENT_BEFORE_ACTION => 'beforeAction'];
        }
        public function beforeAction($event)
        {
            $action = $event->action->id;
            if(in_array($action, $this->actions)){
                $this->controller->enableCsrfValidation = false;
            }
        }    
    }

    然后在Controller中添加Behavior

    public function behaviors()
    {
        return [
            'csrf' => [
                'class' => NoCsrf::className(),
                'controller' => $this,
                'actions' => [
                    'action-name'
                ]
            ]
        ];
    }

数据查询

  • where 多个查询条件示例
    User::find()->where(['and', ['xxx' => 0, 'yyy' => 2], ['>', 'zzz', $time]]);
  • 查询的时候 where 的 OR 和 AND 一起用
    Topic::updateAll(
        ['last_comment_time' => new Expression('created_at')],
        #['or', ['type' => Topic::TYPE, 'last_comment_username' => ''], ['type' => Topic::TYPE, 'last_comment_username' => null]]
        ['and', ['type' => Topic::TYPE], ['or', ['last_comment_username' => ''], ['last_comment_username' => null]]]
    );
  • 嵌套查询,groupBy 分组之后排序功能
    $subQuery = new Query();
    $subQuery->from(PostComment::tableName())->where(['status' => PostComment::STATUS_ACTIVE])->orderBy(['created_at' => SORT_DESC]);
    
    $comment = PostComment::find()->from(['tmpA' => $subQuery])
        ->groupBy('post_id')
        ->all();
    生成的语句是
    SELECT * FROM (SELECT * FROM `post_comment` WHERE `status`=1 ORDER BY `created_at` DESC) `tmpA` GROUP BY `post_id`
  • sql计算字段中相同值重复次数,并排序
    $query = static::find()
        ->select(['package_uuid', 'count(*) AS count', 'cost', 'package_shop_id'])
        ->groupBy('package_uuid');
        ->orderBy('count DESC')
        ->limit(10);
  • 避免select里面的子查询被识别成字段
    $quert = User::find()
        ->select([
              new Expression('count(*) as count , count(distinct mobile) as mnumber')
         ])->asArray()
        ->all();
  • LIKE 查询 单边加%
    ['like', 'name', 'tester'] //会生成 name LIKE '%tester%'。
    ['like', 'name', '%tester', false]  //name LIKE '%tester'
    $query = User::find() ->where(['LIKE', 'name', $id.'%', false]);
  • SQL 随机抽取十名幸运用户
    $query = new Query;             
    $query->select('ID, City,State,StudentName')
          ->from('student')                               
          ->where(['IsActive' => 1])
          ->andWhere(['not', ['State' => null]])
          ->orderBy(['rand()' => SORT_DESC])
          ->limit(10);
  • yii2 多表联查 where条件里 A表字段=B表字段怎么表示?
    #想在where条件里加上c.type=b.type怎么加?
    $res =self::find()
    ->select(['a.id','a.name'])
    ->join('LEFT JOIN','b','b.qid=a.id')
    ->join('LEFT JOIN','c','c.uid=b.uid')
    ->where(['a.state'=>0, 'b.state'=>0, 'c.state'=>0, 'c.uid'=>123456])
    ->asArray()->all();
    
    #方法:
    $query->andWhere(new \yii\db\Expression('c.type = b.type'));
  • where条件中两字段相加或相减
    $query->andWhere(['<', '`updated_at` + `duration`', time()])->all();
  • 输出查询的sql语句
    $query = Weibo::find()->joinWith('account')->where([
        'and',
        ['is_forward' => 0],
        ['status' => Weibo::STATUS_NORMAL_WITH_STAT],
        ['account_open_id' => $account_list],
        ['read_limit_time' => null],
    ])->andWhere("`posted_at` BETWEEN {$now}-`account`.`scrape_time`*60 AND {$now}-`account`.`scrape_time`*60+60");
    
    $commandQuery = clone $query;
    // 输出SQL语句
    echo $commandQuery->createCommand()->getRawSql(); 
    
    $weibo = $query->all();
    输出语句:
    SELECT `weibo`.* FROM `weibo` 
    LEFT JOIN `account` 
    ON `weibo`.`account_open_id` = `account`.`open_id` 
    WHERE ((`is_forward`=0) 
    AND (`status`=1) 
    AND (`account_open_id` IN ('123456789', '987654321', '098765432', '234123455')) 
    AND (`read_limit_time` IS NULL)) 
    AND (`posted_at` BETWEEN 1474946053-`account`.`scrape_time`*60 AND 1474946053-`account`.`scrape_time`*60+60)
  • 搜索的时候添加条件筛选
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    $dataProvider->query->andWhere(['pid' => 0]);
  • 如果要用 find_in_set 需要使用到 Expression 表达式
    User::find()
        ->where(new Expression('FIND_IN_SET(:status, status)'))
        ->addParams([':status' => 1])
        ->all();

MySQL 数据处理

  • yii2 给mysql数据库表添加字段后,立即使用这个字段时会出现未定义的情况(Getting unknown property)

    原因:yii 对数据表结构进行了缓存。

    方法1. 清理掉runtime下的cache缓存之后也可以正常使用这个字段。

    方法2. 修改完表字段后执行

    # 清理指定表结构缓存数据
    Yii::$app->db->getSchema()->refreshTableSchema($tableName);
    
    或
    
    # 清理所有表结构缓存数据
    Yii::$app->db->getSchema()->refresh();

    建议将以上代码添加到修改数据表结构的migration中。

  • 字段去重的三种方法
    static::find()
    ->where([
        'user_id' => $user_id,
    ])
    ->groupBy('uuid')
    ->all();
    
    static::find()
    ->select(['uuid'])
    ->where([
        'user_id' => $user_id,
    ])
    ->distinct()
    ->count();
    
    static::find()->where([
        'user_id' => $user_id,
    ])->count('distinct uuid');
  • 事务
    $transaction = Yii::$app->db->beginTransaction();
    try {
        //... SQL executions
        $transaction->commit();
    } catch (Exception $e) {
        $transaction->rollBack();
    }
    关于事务:
    Yii::$app->db->transaction(function() {
        $order = new Order($customer);
        $order->save();
        $order->addItems($items);
    });
    
    // 这相当于下列冗长的代码:
    
    $transaction = Yii::$app->db->beginTransaction();
    try {
        $order = new Order($customer);
        $order->save();
        $order->addItems($items);
        $transaction->commit();
    } catch (\Exception $e) {
        $transaction->rollBack();
        throw $e;
    }
  • 查找 auth_times 表 type=1 并且 不存在 auth_item 表里面的数据
    // AuthItem.php 关键是 onCondition 方法
    public function getAuthTimes()
    {
        return $this->hasOne(AuthTimes::className(), ['name' => 'name', ])->onCondition([AuthTimes::tableName() . '.type' => 1]);
    }
    
    // AuthTimes.php 文件
    // ......
    AuthItem::find()->joinWith('authTimes')->where([self::tableName() . '.name' => null])->all();
    生成SQL:
    SELECT `auth_item`.* FROM `auth_item` LEFT JOIN `auth_times` ON `auth_item`.`name` = `auth_times`.`name` AND `auth_times`.`type` = 1 WHERE `auth_times`.`name` IS NULL
  • 执行SQL查询并缓存结果
    $styleId = Yii::$app->request->get('style');
    $collection = Yii::$app->db->cache(function($db) use($styleId){
        return Collection::findOne(['style_id'=>$styleId]);
    }, self::SECONDS_IN_MINITUE * 10);
  • 批量插入数据

    第一种方法

    $model = new User();
    foreach($data as $attributes)
    {
         $_model = clone $model;
         $_model->setAttributes($attributes);
         $_model->save();
    }
    第二种方法
    $model = new User();
    foreach($data as $attributes)
    {
          $model->isNewRecord = true;
          $model->setAttributes($attributes);
          $model->save() && $model->id = 0;
    }

URL

假设我们当前页面的访问地址是:http://localhost/public/index.php?r=news&id=1
  • 获取url中的host信息
    # http://localhost
    Yii::$app->request->getHostInfo()
  • 获取url中的路径信息(不包含host和参数)
    Yii::$app->request->getPathInfo()
  • 获取不包含host信息的url(含参数)
    # /public/index.php?r=news&id=1
    Yii::$app->request->url 
    或者
    Yii::$app->request->requestUri
  • 获取完整url(含host以及参数)
    Yii::$app->request->getHostInfo() . Yii::app()->request->url
  • 只想获取url中的参数部分
    # r=news&id=1
    Yii::$app->getRequest()->queryString
  • 获取某个参数的值,比如id
    Yii::$app->getRequest()->getQuery('id'); //get parameter 'id'
  • 获取(除域名外的)首页地址
    # /public/index.php
    Yii::$app->user->returnUrl;
  • 获取Referer
    Yii::$app->request->headers['Referer']
    或者
    Yii::$app->getRequest()->getReferrer()
Tags: Yii2 Yii
转自:https://www.nodelog.cn/content/detail?id=5aad451c90314ca6081f25d9&view=contentDetail
  • 还没有评论,沙发等你来抢
*         

正在加载验证码......