A
A
AlexRas2017-07-17 10:56:58
MySQL
AlexRas, 2017-07-17 10:56:58

How to fix an error in Yii2 when deleting related records from the database?

Hello, I am getting this error:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause' in .....\vendor\yiisoft\yii2\db\Command.php:842

First, it deletes the main record: And then it tries to delete the related table: But there is no user_id column in the user_review table, it uses to_user_id or from_user_id Migrating the user_review table:
SELECT * FROM `user` WHERE `id`=8
DELETE FROM `user_review` WHERE `user_id`=8
public function safeUp()
{
  $tableOptions = null;
  if ($this->db->driverName === 'mysql') {
    $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
  }

  $this->createTable('{{%user_review}}', [
    'id' => $this->primaryKey(),
    'from_user_id' => $this->integer()->notNull(),
    'to_user_id' => $this->integer()->notNull(),
    'stars' => $this->integer()->notNull(),
    'value' => $this->text(),

    'status' => $this->smallInteger()->notNull()->defaultValue(1),

    'created_at' => $this->integer()->notNull(),
    'updated_at' => $this->integer()->notNull(),
  ], $tableOptions);

  $this->addForeignKey('user_review-from_user_id', '{{%user_review}}', 'from_user_id', '{{%user}}', 'id');
  $this->addForeignKey('user_review-to_user_id', '{{%user_review}}', 'to_user_id', '{{%user}}', 'id');
}

Please tell me how to solve it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton, 2017-07-17
@AlexRas

As far as I remember, the deletion of records linked through FOREIGN KEY occurs automatically in MySQL, depending on the ON DELETE parameter. Therefore, it is not very clear where you see the line
Probably, it is called in the model in the afterDelete method. Well, or in the controller, which is bad.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question