Foreign Key Constraint in Laravel Migration - mysql

In Laravel 4, how can I add a foreign key constraint in a migration?
In the migration for mytable (which references foreigntable):
// add Column
$table
->string( 'foreigntable_id', 6 );
// add FK
$table
->foreign( 'foreigntable_id' )
->references( 'id' )
->on( 'foreigntable' );
Error:
[Exception]
SQLSTATE[HY000]: General error: 1005 Can't create table 'mydb.#sql-1a24_2
1a' (errno: 150) (SQL: alter table `mytable` add constraint
mytable_foreigntable_id_foreign foreign key (`foreigntable_id`) references
`foreigntable` (`id`)) (Bindings: array (
))
I assume the problem is that foreigntable does not exist when MySQL tries to add the foreign key constraint to mytable (because the migration that creates foreigntable will only be run after the migration for mytable was finished).
How can I get around this problem?

Actually, I just found the answer myself.
Move the following from the migration for mytable into a new migration:
// add FK
$table
->foreign( 'foreigntable_id' )
->references( 'id' )
->on( 'foreigntable' );
Since the new migration will be run after the migration for mytable, as well as after the migration for foreigntable, both tables will be present at the time that the foreign key constraints is added. Hence it works.

Related

django mysql foreign key constraint fails even though foreign key exists

The error I am getting :
(1452, 'Cannot add or update a child row: a foreign key constraint fails (databasename.Tablename1, CONSTRAINT creative_id_refs_id_a7242fa2 FOREIGN KEY (creative_id) REFERENCES Tablename2 (id))')
I can see that the 'id' exists in Tablename1 though !
Tablename2 has a "created_at" field that specifies when this entry was added. This insertion into Tablename1 happens 20 minutes after this created_at time !!
How is this even possible ? This is so weird.
django version = 1.6.5
mysql engine = InnoDB

Laravel - Can't solve Integrity constraint violation

I have created a new migration to add a column to an existing table and add a foreign key to an existing table.
This is the migration with the new column:
Schema::table( 'events', function ( Blueprint $table ) {
$table->integer( 'category_id' )->unsigned()->after( 'place_id' );
$table->foreign('category_id')->references('id')->on('categories');
} );
When I run the migrate command I get:
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`meetmount`.`#sql-3c8_424`, CONSTRAINT `events_catego
ry_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)) (SQL: alter table `events` add constraint events_category_id_foreign foreign key (`category_id`) r
eferences `categories` (`id`))
and
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`meetmount`.`#sql-3c8_424`, CONSTRAINT `events_catego
ry_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`))
How can I solve?
The cause of the error could be the following:
The parent table categories and/or the child table events already have records in them. As you want to reference the parent table's particular column (id), MySQL will expect the child table to have a value that exists in the parent, hence the integrity constraint violation.
A possible solution (in case the parent is not empty) is to add a default value in the events table for the foreign key column:
$table->integer( 'category_id' )->unsigned()->after( 'place_id' );
$table->foreign('category_id')->references('id')->on('categories')->default(1);
Happened the same with me, but I resolved this adding a default value on creation of column:
$table->integer( 'category_id' )->unsigned()->after( 'place_id' )->default(1);
Make sure the table "categories" has a record with id = 1.

Error when adding foreign key

I had a table named movies which had the fields id as primary key, and two varchars: title and genre.
I created a new table named genres with the int field id as primary key and desription varchar. I changed the field genre in my movies table so I could create a foreign key referencing a genre.
However, Mysql Workbench says there's an error when creating the foreign key.
Here's the statement:
ALTER TABLE `managemovies`.`movies`
ADD CONSTRAINT `genre_reference`
FOREIGN KEY (`genre` )
REFERENCES `managemovies`.`genres` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
, ADD INDEX `genre_reference_idx` (`genero` ASC) ;
Error:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`managemovies`.`#sql-3ba_2b`, CONSTRAINT `genre_reference` FOREIGN KEY (`genre`) REFERENCES `genres` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
SQL Statement: [... same statement than above ... ]
ERROR: Error when running failback script. Details follow.
ERROR 1046: No database selected
SQL Statement:
CREATE TABLE `movies` [...]
[... the errors above repeated again ...]
clear your table contents and try adding foreign key.
if your table contain data which not matching the foreign key field value you will see this error ...
It looks like your table movies has data in genre column which is not present in genres.id column.
Your statement should work after removing the invalid data.
Hope it helps
Vishad
I have faced same issue i got resolved later..
for this answer is simple you just need to add atleast a row of values in both tables then try to add the foreign key

Cannot add or update a child row: a foreign key constraint fails webERp

I use WebERP in my 1and1 account, when I migrate my database to another 1and1 database I get this error:
SQL query:
--
-- Constraints for table `chartdetails`
--
ALTER TABLE `chartdetails` ADD CONSTRAINT `chartdetails_ibfk_1` FOREIGN KEY ( `accountcode` )
REFERENCES `chartmaster` ( `accountcode` ) ,
ADD CONSTRAINT `chartdetails_ibfk_2` FOREIGN KEY ( `period` ) REFERENCES `periods` ( `periodno` )
MySQL said:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`dbxxxxxxxxx/#sql- 376_3fa4f12`, CONSTRAINT `chartdetails_ibfk_2` FOREIGN KEY (`period`) REFERENCES `periods` (`periodno`))
But the original file just work fine.
I got the same Error when i migrate. I resolved this error in 3 ways. You can resolve your error on any one of them or an all. This happens because of no data insret query happens before you alter.
• Put Alter table queries on last of all other queries.
• Twice check for the presence of data where the primary key is present
• Install fresh DB later insert in hierarchical order like chart master first and later chart detail insert queries.
Note: DB wont allow you to delete or insert when you try to change db queries. Keep backups of DB before making any changes.

MySQL Create table with indexes error

Ok, so I am creating tables in MySQL with indexes and foreign keys. I use MySQL Workbench to create the tables and then have it forward engineer a SQL create script (I do better in a visual DB environment than just writing out the SQL code by hand right away).
The problem is many times when I import the sql script into mysql, I get the classic eror:
#1005 - Can't create table 'db.tablename' (errno: 121)
I've managed to figure out the problem each time, usually index/foreign key related, but now I'm starting to get irritated at having to fix it each time. I don't really understand what the problem is (especially when a MySQL product is creating sql code for its own database). Below is some code that typically causes the problem.
CREATE TABLE IF NOT EXISTS `db`.`groupMembers` (
`groupMembersID` INT NOT NULL AUTO_INCREMENT ,
`groupID` INT NOT NULL ,
`userID` INT NULL ,
PRIMARY KEY (`groupMembersID`) ,
INDEX `group` (`groupID` ASC) ,
INDEX `user` (`userID` ASC) ,
CONSTRAINT `group`
FOREIGN KEY (`groupID` )
REFERENCES `db`.`groups` (`groupsID` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `user`
FOREIGN KEY (`userID` )
REFERENCES `db`.`users` (`usersID` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
The error usually comes from the first INDEX definition - even when I take out the index definition, I just get the error at the the first foreign key constraint definition. I've checked, and the foreign key remote column and the local column are the same data-type and size.
"errno 121 means a duplicate key error"
Constraints must have an unique name in the database, you might wanna change your FK names. Like so, FK_groupMembers_group and FK_groupMembers_user.