2

Trying to use the Yii2 TimestampBehavior but when saving it will return a doesn't have default value error.

The values are not required in the rules. The DB column is a INT(11). As I needed to save several rows I use batchInsert() for this.

When I add a the value with time() it will save everything to the DB.

public function behaviors()
{
  return [
       'timestamp' => [
           'class' => TimestampBehavior::className(),
           'attributes' => [
               ActiveRecord::EVENT_BEFORE_INSERT => 'created_at',
               ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at',
           ],
           'value' => new Expression('NOW()'),
       ],
       'blameable' => [
           'class' => BlameableBehavior::className(),
           'createdByAttribute' => 'created_by',
           'updatedByAttribute' => 'updated_by',
        ],
   ];
}

Yii::$app->db->createCommand()->batchInsert( 'table_cms',
     [
        //all fields but not the timestamps
     ],
     [
        //rows here
     ])
     ->execute();

1 Answer 1

2

batchInsert() does not support ActiveRecord features, so TimestampBehavior has no effect here. TimestampBehavior will be used if you call save(). In your case you need to pass timestamp manually.

doesn't have default value probably means that you're using MySQL in strict mode - it will warn you if you will try to add record without specifying all fields without default values.

Sign up to request clarification or add additional context in comments.

1 Comment

Okay I was afraid that batchInsert did not support the behavior, well I will do it manually. Thanks for the info :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.