0

I have a problem when I use batchInsert() to insert multiple records.

Yii::$app->db->createCommand()->batchInsert($this->model->tableName(), $columns, $rows)->execute()

And I has implemented the TimestampBehavior in my BaseModel

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        [
            'class' => TimestampBehavior::className(),
            'createdAtAttribute' => 'createdAt',
            'updatedAtAttribute' => 'updatedAt'
        ]
    ];
}

But when I executed then it's not working?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
dangchithao
  • 613
  • 2
  • 8
  • 24

2 Answers2

0

This behavior is attached to ActiveRecord and executed during its life cycle while batchInsert executes raw SQL query so you can not use it there.

You can generate this columns values though.

Add 'createdAt' and 'updatedAt' to $columns.
For every row in $rows add time() as value for createdAt and updatedAt column.

This simply fills these columns with current unix timestamp.

Bizley
  • 17,392
  • 5
  • 49
  • 59
0

Yii Behaviors are a functionality directly related to Active Record.

And Active Record is fundamentally different than the Query Builder (which you get by calling Yii::$app->db->createCommand()). They are two different ways of working with records in the database.

So the simplest answer to your question is that you can not use Yii Behaviors when working with the Query Builder.

Dzhuneyt
  • 8,437
  • 14
  • 64
  • 118