Answer the question
In order to leave comments, you need to log in
How to render common migration columns in Yii2?
I have two migrations:
(1):
<?php
use yii\db\Migration;
class m211025_183630_create_user_table extends Migration
{
public function safeUp()
{
$this->createTable('{{%user}}', [
'id' => $this->primaryKey(),
'email' => $this->string()->notNull()->unique(),
'password_hash' => $this->string()->notNull(),
'auth_key' => $this->string()->notNull(),
'created_by' => $this->integer()->null(),
'updated_by' => $this->integer()->null(),
'status' => $this->smallInteger()->notNull()->defaultValue(10),
'updated_at' => $this->integer()->notNull(),
'created_at' => $this->integer()->notNull(),
], Yii::$app->params['tableOptions']);
$this->addForeignKey(
'fk-user-created_by',
'user',
'created_by',
'user',
'id',
'SET NULL',
'CASCADE'
);
$this->addForeignKey(
'fk-user-updated_by',
'user',
'updated_by',
'user',
'id',
'SET NULL',
'CASCADE'
);
}
public function safeDown()
{
$this->dropForeignKey('fk-user-created_by', 'user');
$this->dropForeignKey('fk-user-updated_by', 'user');
$this->dropTable('{{%user}}');
}
}
<?php
use yii\db\Migration;
class m211025_191412_create_post_table extends Migration
{
public function safeUp()
{
$this->createTable('{{%post}}', [
'id' => $this->primaryKey(),
'title' => $this->string()->notNull(),
'content' => $this->text()->null(),
'image' => $this->string()->null(),
'created_by' => $this->integer()->null(),
'updated_by' => $this->integer()->null(),
'status' => $this->smallInteger()->notNull()->defaultValue(10),
'updated_at' => $this->integer()->notNull(),
'created_at' => $this->integer()->notNull(),
], Yii::$app->params['tableOptions']);
$this->addForeignKey(
'fk-post-created_by',
'post',
'created_by',
'user',
'id',
'SET NULL',
'CASCADE'
);
$this->addForeignKey(
'fk-post-updated_by',
'post',
'updated_by',
'user',
'id',
'SET NULL',
'CASCADE'
);
}
public function safeDown()
{
$this->dropForeignKey('fk-post-created_by', 'post');
$this->dropForeignKey('fk-post-updated_by', 'post');
$this->dropTable('{{%post}}');
}
}
Answer the question
In order to leave comments, you need to log in
create a MigrationWithDates class - override the createTable method
which will insert into each created_at table, etc.
class MigrationWithDates extends Migrations{
public function createTable($tableNane, array $data){
$addDates = [
'created_by' => $this->integer()->null(),
'updated_by' => $this->integer()->null(),
'status' => $this->smallInteger()->notNull()->defaultValue(10),
'updated_at' => $this->integer()->notNull(),
'created_at' => $this->integer()->notNull(),
];
$mergedData = array_merge ($data, $addDates );
parent::createtable($tableName, $mergedData);
}
}
Alternatively, you can try to rewrite the migration component and use your own
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question