Reputation: 303
I'm new to Yii2 framework
, so. I need to specify 3 categories
by using Yii2 migration
.
F.e: user enters a form and in that form there is a dropdown where he can select the category
from the specified ones, which is in the database and according to that category select items
, which is also stored in a database.
I've created all the tables with foreign keys
by using migration, here is the category
table:
<?php
use yii\db\Migration;
class m170425_115637_sale extends Migration
{
public function up()
{
$this->createTable('sale', [
'id' => $this->primaryKey(),
'item_id' => $this->integer(11)->notNull(),
'customer_name' => $this->string(255)->notNull(),
'customer_surname' => $this->string(255)->notNull(),
'customer_phone' => $this->string(255)->notNull(),
'customer_email' => $this->string(255)->notNull(),
'code' => $this->string(255)->notNull(),
'sign' => $this->boolean(),
'comnent' => $this->text(),
]);
// creates index for column `item_id`
$this->createIndex(
'idx-post-item_id',
'sale',
'item_id'
);
// add foreign key for table `user`
$this->addForeignKey(
'fk-post-item_id',
'sale',
'item_id',
'item',
'id',
'CASCADE'
);
}
public function down()
{
$this->dropTable('sale');
}
And here is item
table:
<?php
use yii\db\Migration;
class m170425_114148_item extends Migration
{
public function up()
{
$this->createTable('item', [
'id' => $this->primaryKey(),
'category_id' => $this->integer(11)->notNull(),
'name' => $this->string(255)->notNull(),
'price' => $this->double(),
]);
// creates index for column `category_id`
$this->createIndex(
'idx-post-category_id',
'item',
'category_id'
);
// add foreign key for table `category`
$this->addForeignKey(
'fk-item-category_id',
'item',
'category_id',
'category',
'id',
'CASCADE'
);
}
public function down()
{
$this->dropTable('item');
}
I hope you understand the problem, thanks for the help!
Upvotes: 1
Views: 1980
Reputation: 18021
If you want to add some table data in the migration you can use batchInsert().
$this->batchInsert('category', ['name'], [['category1'], ['category2'], ['category3']]);
This adds 3 rows to the category
table by inserting in each given value for name
column.
If you want to add more columns at once do it like that:
$this->batchInsert('category', ['name', 'another'], [
['category1', 'aaa'],
['category2', 'bbb'],
['category3', 'ccc']
]);
Upvotes: 3