温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

yii2怎么根据条件设定指定值

发布时间:2021-09-15 21:16:43 来源:亿速云 阅读:239 作者:chen 栏目:大数据

本篇内容主要讲解“yii2怎么根据条件设定指定值”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“yii2怎么根据条件设定指定值”吧!

gii自动生成的_form.php文件中,我们可以根据代码$model->isNewRecord 返回的值,来判断当前是增加还是更新,在form.php文件中,还可以根据它的属性值给字段input框赋予默认值

connect字段为多选框字段,前台传到后台的数据默认是数组格式。该字段对应是让tostring方法处理,先把它的值赋给静态变量$connect,然后在beforeSave中把数组格式化成字符串,在返回,存入数据库。

<?php

namespace backend\models;

use Yii;

use \yii\db\ActiveRecord;

class Newdocument extends ActiveRecord
{

    public function beforeSave($insert){
        if(parent::beforeSave($insert)){
            if($this->isNewRecord){//判断是更新还是插入
                $this->connect = implode(',', $this->connect);
                $this->create_time = time();

            }else{
                $this->update_time = time();
                $this->connect = implode(',', $this->connect);
            }
           return true;
        }else{

            return false;
        }
    }
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'document';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [[  'create_time','update_time'], 'integer'],

            ['connect','tostring'],
        ];
    }

    public function tostring(){//可通过方法单独控制某个字段,也可以直接通过beforesave方法控制
            //if($this->isNewRecord){//判断是更新还是插入
                //$this->connect = implode(',', $this->connect);
            //}else{
               // $this->connect = implode(',', $this->connect);
            //}
    }

到此,相信大家对“yii2怎么根据条件设定指定值”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

yii
AI