Данное поведение решил внедрить в расширение https://github.com/sadovojav/yii2-gallery-module.
Миграция:
Код: Выделить всё
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
}
/**
* Create {{%gallery}} table
*/
$this->createTable('{{%gallery}}', [
'id' => Schema::TYPE_PK,
'status' => Schema::TYPE_SMALLINT . '(1) NOT NULL DEFAULT 0',
'created' => Schema::TYPE_DATETIME . ' NOT NULL',
'updated' => Schema::TYPE_DATETIME . ' NOT NULL',
], $tableOptions);
$this->createIndex('idx_gallery_id_status', '{{%gallery}}', 'id, status');
/**
* Create {{%galleryLang}} table
*/
$this->createTable('{{%galleryLang}}', [
'id' => Schema::TYPE_PK,
'gallery_id' => Schema::TYPE_INTEGER . ' NOT NULL',
'language' => Schema::TYPE_STRING . '(6) NOT NULL',
'name' => Schema::TYPE_STRING . '(50) NOT NULL',
'KEY `gallery_id` (`gallery_id`)',
'KEY `language` (`language`)',
], $tableOptions);
$this->addForeignKey('galleryLang_ibfk_1', '{{%galleryLang}}', 'gallery_id', '{{%gallery}}', 'id', 'CASCADE');
/**
* Create {{%gallery_file}} table
*/
$this->createTable('{{%gallery_file}}', [
'id' => Schema::TYPE_PK,
'galleryId' => Schema::TYPE_INTEGER . ' NOT NULL',
'file' => Schema::TYPE_STRING . '(255) NOT NULL',
'position' => Schema::TYPE_INTEGER . '(1) DEFAULT 0',
], $tableOptions);
$this->createIndex('idx_gallery_galleryId', '{{%gallery_file}}', 'galleryId');
$this->addForeignKey('fk_gallery_file_galleryId', '{{%gallery_file}}', 'galleryId', '{{%gallery}}',
'id','CASCADE','RESTRICT');
/**
* Create {{%gallery_fileLang}} table
*/
$this->createTable('{{%gallery_fileLang}}', [
'id' => Schema::TYPE_PK,
'gallery_file_id' => Schema::TYPE_INTEGER . ' NOT NULL',
'language' => Schema::TYPE_STRING . '(6) NOT NULL',
'caption' => Schema::TYPE_STRING . '(255)',
'KEY `gallery_file_id` (`gallery_file_id`)',
'KEY `language` (`language`)',
], $tableOptions);
$this->addForeignKey('gallery_fileLang_ibfk_1', '{{%gallery_fileLang}}', 'gallery_file_id', '{{%gallery_file}}', 'id', 'CASCADE');
}
Код: Выделить всё
class Gallery extends yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%gallery}}';
}
/**
* @return array
*/
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created',
'updatedAtAttribute' => 'updated',
'value' => new Expression('NOW()'),
],
'ml' => [
'class' => MultilingualBehavior::className(),
'languages' => Yii::$app->params['translatedLanguages'],
'langForeignKey' => 'gallery_id',
'tableName' => '{{%galleryLang}}',
'attributes' => [
'name',
],
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'name_en', 'name_ru'], 'required'],
['status', 'integer'],
[['created', 'updated'], 'safe'],
[['name', 'name_en', 'name_ru'], 'string', 'max' => 50],
];
}