rageframe2-Yii2常用语法


日期查询

        use yii\db\Expression;


        $date = "2000-01-01";

        Comp::find()->andFilterWhere(['>=', 'date', new Expression($date)])



打印最后一次sql

        $commandQuery = clone $query;

        var_export(['sql' => $commandQuery->createCommand()->getRawSql()]);


常用sql

       读: https://blog.csdn.net/weixin_33742618/article/details/91966388

       写:https://blog.csdn.net/dzyweer/article/details/106906057

       官方写:https://www.yiichina.com/doc/api/2.0/yii-db-command


      新增/更新

            Yii::$app->db->createCommand()

                ->insert(Yii::$app->db->tablePrefix . 'sendcode', $data)

                ->execute();

             Yii::$app->db->createCommand()->update(Yii::$app->db->tablePrefix . 'users',

                ['coin'=> $coin+$user_coin], ['id' => 1])

                ->execute();


            Yii::$app->params['none_refresh'] = true; //true,fasle:隐藏/显示列表刷新返回



        子查询+in格式化

            ->andWhere(['not in', 'upper',

                \common\helpers\ArrayHelper::getShiftOne(

                    Member::find()->select('id')->where(['=','upper', $id])->asArray()->all()

                )

            ])


生成当前应用下的路由地址

        Url::to(['users-live/addvideo'])

        如当前在:/backend/live/users-live/index,则生成为:/backend/live/users-live/addvideo



加载弹窗

        php:$this->message('测试', '', $msgType = 'error');
        js:toastr.error(data.msg);



模型中当指定字段为空时可以选择不更新,继续复用原来字段值,只需加入此方法:


        public function validateClientSecret($attribute, $params)

        {

            // 当 Client Secret 为空时,赋值 Client Secret 为原先的值

            if (empty($this->$attribute)) {

                $this->$attribute = $this->getOldAttribute($attribute);

            }

        

            $this->$attribute = $this->getOldAttribute($attribute);

        }


或者直接使用事件:


        use yii\behaviors\AttributeBehavior;

        

        public function behaviors()

        {

            return [

        

                [

                    'class' => AttributeBehavior::className(),

                    'attributes' => [

                        ActiveRecord::EVENT_BEFORE_INSERT => ['agent_tree'],  //插入时 需要操作的字段

                        ActiveRecord::EVENT_BEFORE_UPDATE => ['agent_tree'],  //更新时 需要操作的字段

                    ],

                    'value' => function ($event) {


                      //这里假如一种格式化方式,返回fasle为空

                        $AgentTree = Yii::$app->services->merchantAgent->bindAgentTree($this->agent_tree);


                        if (false === $AgentTree){

                            //沿用原来的值完成更新

                            $AgentTree = $this->getOldAttribute('agent_tree');


                            //更新完成后可以返回提示信息

                            $this->message('xxx字段为空,操作失败','');

                        }

        

                        return $AgentTree;

                    },

                ],

        

            ];

        }




鼎云博客
  • 最新评论
  • 总共0条评论