Php foreign key constraint fails

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

foreign key constraint fails with php artisan db:seed #64

foreign key constraint fails with php artisan db:seed #64

Comments

I am still trying to install. with the $ php artisan db:seed
I get another error.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update
a child row: a foreign key constraint fails ( oz . categories , CONSTRAINT
categories_language_id_foreign FOREIGN KEY ( language_id ) REFERENCES la nguages ( id )) (SQL: insert into categories ( color , description , l anguage_id , title , slug , updated_at , created_at ) values (#459016,
Qui ea repudiandae id magni ut et., 2, Enim ut sint vel., enim-ut-sint-vel,
2017-12-31 15:00:47, 2017-12-31 15:00:47))

In PDOStatement.php line 107:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update
a child row: a foreign key constraint fails ( oz . categories , CONSTRAINT
categories_language_id_foreign FOREIGN KEY ( language_id ) REFERENCES la nguages ( id ))

In PDOStatement.php line 105:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update
a child row: a foreign key constraint fails ( oz . categories , CONSTRAINT
categories_language_id_foreign FOREIGN KEY ( language_id ) REFERENCES la nguages ( id ))

The text was updated successfully, but these errors were encountered:

Источник

Фикс «Mysql error 1452 — Cannot add or update a child row: a foreign key constraint fails» при миграции в Doctrine 1.2

В ситуациях, когда необходимо совершать действия над таблицей, которая уже содержит в себе какие-либо данные, может возникнуть неприятная ошибка: «Mysql error 1452 — Cannot add or update a child row: a foreign key constraint fails«.

Возникает она вследствие того, что мы пытаемся изменить существующую запись таким образом, что нарушается целостность.

Например, присвоение полю ключа, который не существует в родительской таблице. Или создание нового внешнего ключа для поля, которое не должно быть NULL, в таблице, которая уже содержит некоторое количество записей. Последняя проблема у меня и возникла. Необходимо было решение, и оно было найдено.

Решение простое как пять копеек. Нам необходимо избавиться от NULL-значений в поле, на которое навешивается внешний ключ.

Читайте также:  Typescript any vs unknown vs never

Предположим, что вы уже отредактировали схему соответствующим образом и она имеет примерно следующее содержание:

Human: columns: name: < type: string(255), notnull: true >human_status_id: < type: integer, notnull: true >relations: HumanStatus: local: human_status_id foreign: id onDelete: CASCADE HumanStatus: columns: name:

После успешной генерации миграций должны появиться два файла миграций: один будет содержать создание таблиц, а вторая создание связей между ними. Именно второй файл мы и будем редактировать. Нам это никто не запрещает.

Итак, как я уже сказал, нам необходимо избавиться от NULL-значений. Для этого мы поправим вторую миграцию примерно таким образом:

public function up() < $conn = Doctrine_Manager::getInstance()->getCurrentConnection(); $oHumanStatus = new HumanStatus(); $oHumanStatus->setName('Temp'); $oHumanStatus->save(); Doctrine_Query::create() ->update() ->from('Human') ->set('human_status_id', $oHumanStatus->getId()) ->execute(); $this->createForeignKey('human', 'human_human_status_id_human_status_id', array( 'name' => 'human_human_status_id_human_status_id', 'local' => 'human_status_id', 'foreign' => 'id', 'foreignTable' => 'human_status', 'onUpdate' => '', 'onDelete' => 'CASCADE', )); $this->addIndex('human', 'human_human_status_id', array( 'fields' => array( 0 => 'human_status_id', ), )); >

Думаю, основная идея понятна. Если нет нужды в создании новой записи в таблице HumanStatus, можно поискать уже существующие. Все зависит от вашей ситуации.

Далее накатываем обе миграции. Все должно пройти успешно. Если нет — читайте мануалы дальше. Возможно, это не ваш случай.

P.S. Не оставляйте die() в up() или down() методах миграции. Иначе она не накатится.

Источник

How to fix MySQL ERROR 1452 a foreign key constraint fails

The MySQL ERROR 1452 happens when you try to execute a data manipulation query into a table that has one or more failing foreign key constraints.

The cause of this error is the values you’re trying to put into the table are not available in the referencing (parent) table.

Let’s see an example of this error with two MySQL tables.

Suppose you have a Cities table that contains the following data:

Then, you create a Friends table to keep a record of people you know who lives in different cities.

You reference the id column of the Cities table as the FOREIGN KEY of the city_id column in the Friends table as follows:

                        In the code above, a CONSTRAINT named friends_ibfk_1 is created for the city_id column, referencing the id column in the Cities table.

This CONSTRAINT means that only values recoded in the id column can be inserted into the city_id column.

(To avoid confusion, I have omitted the id column from the Friends table. In real life, You may have an id column in both tables, but a FOREIGN KEY constraint will always refer to a different table.)

When I try to insert 5 as the value of the city_id column, I will trigger the error as shown below:

   As you can see, the error above even describes which constraint you are failing from the table.

Based on the Cities table data above, I can only insert numbers between 1 to 4 for the city_id column to make a valid INSERT statement.

The same error will happen when I try to update the Friends row with a city_id value that’s not available.

Take a look at the following example:

  • You add the value into the referenced table
  • You disable the FOREIGN_KEY_CHECKS in your server

The first option is to add the value you need to the referenced table.

In the example above, I need to add the id value of 5 to the Cities table:

                              Now I can insert a new row in the Friends table with the city_id value of 5 :

Disabling the foreign key check

The second way you can fix the ERROR 1452 issue is to disable the FOREIGN_KEY_CHECKS variable in your MySQL server.

You can check whether the variable is active or not by running the following query:

This variable causes MySQL to check any foreign key constraint added to your table(s) before inserting or updating.

You can disable the variable for the current session only or globally:

     Now you can INSERT or UPDATE rows in your table without triggering a foreign key constraint fails :

After you’re done with the manipulation query, you can set the FOREIGN_KEY_CHECKS active again by setting its value to 1 :

     But please be warned that turning off your FOREIGN_KEY_CHECKS variable will cause the city_id column to reference a NULL column in the cities table.

It may cause problems when you need to perform a JOIN query later.

Now you’ve learned the cause of ERROR 1452 and how to resolve this issue in your MySQL database server. Great work! 👍

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Источник

Не удаляется запись из таблицы: a foreign key constraint fails

#1451 — Cannot delete or update a parent row: a foreign key constraint fails (`admin_bd`.`pics`, CONSTRAINT `fk_pics_h1` FOREIGN KEY (`house_id`) REFERENCES `houses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)

Понимаю, что дело в связях, но не знаю, как убрать эту связь по house_id с fk_pics_h1? Подскажите, плз.

Не удаляется запись из таблицы: a foreign key constraint fails
Здравствуйте, дорогие друзья. Подскажите пожалуйста, как решить следующий вопрос: После.

Cannot add or update a child row: a foreign key constraint fails
Такая проблема: не добавляется значение в таблицу через запрос mysql_query. Если тоже самое делать.

Cannot add or update a child row: a foreign key constraint fails
Всем привет. Буду рад помощи. Столкнулся с ошибкой. 123Cannot add or update a child row: a.

#1452 — Cannot add or update a child row: a foreign key constraint fails
При добавлении данных выдает эту ошибку: #1452 — Cannot add or update a child row: a foreign key.

На запись в таблице houses, которую вы хотите удалить ссылаются записи из таблицы pics, нужно не убирать связь, а изменить параметры ON DELETE и ON UPDATE для таблицы pics относительно внешнего ключа house_id, если вам нужно что бы записи из pics, принадлежащие house_id, при удалении из house тоже удалялись то ON UPDATE CASCADE ON DELETE CASCADE, если не нужно что бы удалялись, то ON UPDATE SET NULL ON DELETE SET NULL.
Удалите внешний ключ и создайте новых с правильными параметрами.

ЦитатаСообщение от zebulun Посмотреть сообщение

На запись в таблице houses, которую вы хотите удалить ссылаются записи из таблицы pics, нужно не убирать связь, а изменить параметры ON DELETE и ON UPDATE для таблицы pics относительно внешнего ключа house_id, если вам нужно что бы записи из pics, принадлежащие house_id, при удалении из house тоже удалялись то ON UPDATE CASCADE ON DELETE CASCADE, если не нужно что бы удалялись, то ON UPDATE SET NULL ON DELETE SET NULL.
Удалите внешний ключ и создайте новых с правильными параметрами.

ALTER TABLE `admin_bd`.`pics` DROP FOREIGN KEY `fk_pics_h1` ALTER TABLE `admin_bd`.`pics` ADD CONSTRAINT `fk_pics_h1` FOREIGN KEY (`house_id`) REFERENCES `admin_bd`.`houses`(`id`) ON UPDATE CASCADE ON DELETE CASCADE

Cannot add or update a child row: a foreign key constraint fails
Доброе время суток. Являюсь полнейшим профаном в MySql и в базах данных собственно тоже.

Cannot add or update a child row: a foreign key constraint fails
Здравствуйте! Изучая MySQL и PHP столкнулся с такой вот проблемкой: Cannot add or update a child.

Cannot add or update a child row: a foreign key constraint fails
Вот код ошибки: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrity ConstraintViolationException.

Источник

Ошибка cannot add or update a child row при создании связи между таблицами, как исправить?

9fec018b7310429ca9356ff43020beac.jpg

Вот такая ошибка

в обоих столбцах есть записи, по 2, внешний ключ индекс, первичный ключ автоинкримент. Как не соединяю уже, вот такая ошибка. Что не так настроил в таблицах?

qonand

Melkij описал причину ошибки, соответственно что бы устранить ее Вам нужно изменить данные:
1. Либо вообще удалить все несоответствующие данные, например:

DELETE FROM add_photos_store WHERE magazin NOT IN (SELECT id FROM stores);

2. Либо установить значение для magazin в таблица add_photos_store в NULL (если конечно Ваше поле может принимать такое значение), например:

UPDATE add_photos_store SET magazin = NULL WHERE magazin NOT IN (SELECT id FROM stores);

Удалил все магазины, вообщем связь получилась. Но что бы я не выставлял в ON UPDATE и ON DELETE, все равно при добавлении в таблицу add_photos_store данных через админку, такая ошибка «Cannot add or update a child row: a foreign key constraint fails (`freeman_domolux`.`add_photos_store`, CONSTRAINT `add_photos_store_ibfk_1` FOREIGN KEY (`magazin_id`) REFERENCES `stores` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)» это я перевожу «Невозможно добавить или обновить дочернюю строку: ограничение внешнего ключа не выполняется» ограничения я не ставил, почему такая ошибка? Но зато через phpmyadmin инфу можно вставить в add_photos_store и там я выбираю при вставке id магазина, все отображается но все одинаковое в каждом магазине, это из за выборки. Нужно писать выборку так select * from add_photos_store where magazin_id = n, где n — id магазина т.е magazin_id = id но вылазит такая ошибка «Unknown column ‘magazin_id’ in ‘where clause'». Что не так делаю?

Источник

Оцените статью