当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP yii实现model添加默认值的方法(两种方法)

PHP yii实现model添加默认值的方法(两种方法)

2017年12月12日  | 移动技术网IT编程  | 我要评论

胜利者岗哨,儿童摄影作品,mysql触发器

yii实现model添加默认值的方法(2种方法)

这篇文章主要介绍了yii实现model添加默认值的方法,结合实例分析了在rules()方法及在beforesave()方法中设定两种实现技巧,对大家也许有帮助,

本文实例讲述了yii实现model添加默认值的方法。分享给大家供大家参考,具体如下:

yii model 继承自cactiverecord

有些字段可能不会出现在表单中,而需要在程序中加入。如订单编号,时间戳,操作的user_id等等。

以下二种方法:

1、在rules()方法中设定:

public function rules()
{
 // note: you should only define rules for those attributes that
 // will receive user inputs.
 return array(
  array('start, end', 'required'),
  array('user_id', 'numerical', 'integeronly'=>true),
  array('timestamp','default','value'=>date('y-m-d h:i:s')),
  // the following rule is used by search().
  // please remove those attributes that should not be searched.
  array('id, start, end, user_id, timestamp', 'safe', 'on'=>'search'),
 );
}

 2、在beforesave()方法中设定:

function beforesave()
{
 $this->user_id = yii::app()->user->id;
 return true;
}

需要注意的是,beforesave()方法需要return true,否则不会保存。

希望本文所述对大家基于yii框架的php程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网