A
A
Airslip2017-01-20 12:49:06
Yii
Airslip, 2017-01-20 12:49:06

How to bind table fields in migrations?

Greetings, I ask for help, I have been trying to solve the problem for more than one day.
I'm using a migration file in Yii2 to create a database, all tables and elements are created normally, but when I try to bind one field to another, the console writes an error: "errno 150 foreign key constraint is incorrectly formed". What am I doing wrong, tell me please?

public function up()
{
  $tableOptions = null;
  if ($this->db->driverName === 'mysql') {
    $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
  }
  // Организации
  $this->createTable('{{%company}}', [
    'id' => $this->primaryKey(),
    'name' => $this->string(),
    'code' => $this->string(),
    'city' => $this->string(),
    'address' => $this->string(),
    'schedule' => $this->string(),
    'link' => $this->string(),
  ], $tableOptions);

  // Телефоны
  $this->createTable('{{%phone}}', [
    'id' => $this->primaryKey(),
    'company' => $this->string(),
    'number' => $this->string(),
  ], $tableOptions);

  $this->addForeignKey("fk-phone-company", "{{%phone}}", "company", "{{%company}}", "name", 'SET NULL', 'RESTRICT');
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2017-01-20
@Airslip

Your fields "{{%phone}}.company" and "{{%company}}.name" are not indexed, so no external link is created.
And why are you linking on the fields "{{%phone}}.company" and "{{%company}}.name"? You also have a primaryKey in each table.
I would do like this:

public function up()
{
  $tableOptions = null;
  if ($this->db->driverName === 'mysql') {
    $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
  }
  // Организации
  $this->createTable('{{%company}}', [
    'id' => $this->primaryKey(),
    'name' => $this->string(),
    'code' => $this->string(),
    'city' => $this->string(),
    'address' => $this->string(),
    'schedule' => $this->string(),
    'link' => $this->string(),
  ], $tableOptions);

  // Телефоны
  $this->createTable('{{%phone}}', [
    'id' => $this->primaryKey(),
    'company_id' => $this->integer(),
    'number' => $this->string(),
  ], $tableOptions);
  $this->createIndex('idx-phone-company_id', '{{%phone}}', 'company_id');
  $this->addForeignKey("fk-phone-company", "{{%phone}}", "company_id", "{{%company}}", "id", 'SET NULL', 'RESTRICT');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question