Yii说它可以自动设置时间戳' created_at':http://www.yiiframework.com/doc-2.0/guide-concept-behaviors.html#using-timestampbehavior
但是,每次创建记录时,时间都是空白的:
$ yii kw/test
1437683634
mysql> select * from ad_group_keyword_network where ad_group_keyword_id = 1;
+---------------------+-
| created_at |
+---------------------+-
| 0000-00-00 00:00:00 |
| 0000-00-00 00:00:00 |
+---------------------+-
public function actionTest() {
$agkn = new AdGroupKeywordNetwork();
$agkn->save();
echo $agkn->created_at;
我尝试使用Schema::TYPE_TIMESTAMP
并更改了字段,并尝试使用Schema::TYPE_DATETIME
。它们都在保存后返回字段中的整数时间戳,但数据库中的时间全是0。
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => [],
答案 0 :(得分:2)
您的created_at
必须是INT(11)类型。我认为你使用的是TIMESTAMP类型,它不起作用。
答案 1 :(得分:1)
根据Marc和Michael的说法,我使用了它并且它起作用了。
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => null,
'value' => function(){return date(DATE_ATOM);},
$ yii kw/test
2015-07-23T16:59:17-04:00
...
+---------------------+
| created_at |
+---------------------+
| 2015-07-23 16:59:17 |
答案 2 :(得分:0)
$ value 是将用于生成时间戳的表达式,默认情况下它将使用time()
的值,除非您为其分配一个返回时间戳值的匿名函数:
'timestamp' => [
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'created_at',
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at',
],
'value' => function() { return date('U'); },
],
或表示数据库表达式的yii \ db \ Expression对象:
'timestamp' => [
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'created_at',
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at',
],
'value' => new \yii\db\Expression('NOW()'), // MySql exp
],