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);
            //}
    }




}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值