开发者

SQL Error: 1452: Cannot add or update a child row: a foreign key constraint fails

I have two tables in my database:

  1. order;
  2. course.开发者_如何转开发

order has a column courseid which references column id of the course table. Whenever I tried to do saveAll() in CakePHP the above SQL error will display and data wont be saved.


What it sounds is that between your tables you have foreign key constraint in the database. This mean that in the the column course_id you cannot insert values different than ids from the foreign table.

The error above means that when you post your data the foreign field is empty or missing.

What to look for: 1. Check if in your database the foreign field in the child table can accept NULL. If you have dropdown with values and the default option is empty if the field doesn't accept NULL this error could occur 2. Check your data in the controller if you pass the variable in example: $this->data['Order']['course_id'] if it's empty or missing see point 1.


I am going to respond just for the sake of anyone else with a similar issue looking for an answer. Working with ORM in other frameworks, I made the mistake of trying to assign roles or other data before saving what I was adding a role to. Example:

Creating a new user-

    $user = ORM::factory('user');
    $user->username = 'SomeoneSpecial";

    if ($user->add(ORM::factory('role', 'login') && $user->save() ) {
        // continue on with code
    }

The user is created, however in trying to add the role before the user is saved, you end up with a user without a role and that exact error being spit back out at you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜