简体   繁体   中英

Laravel MySQL Cannot insert null in nullable foreign key

I'm going crazy with this error/bug. I'm using Laravel 4.2 to develop an application in which I have a table created like this:

Schema::create('stock_items', function(Blueprint $table){
  ....
  $table->integer('color_id')->unsigned()->nullable();
  $table->integer('size_id')->unsigned()->nullable();
  ....
  $table->foreign('color_id')->references('id')->on('colors');
  $table->foreign('size_id')->references('id')->on('sizes');
});

Both columns can be null but when I insert something like this:

$stock_item->color_id = NULL;
$stock_item->size_id = NULL;

I get a MySQL Error telling me: Could not insert: Cannot add or update a child row: a foreign key constraint fails

BUT if I run the exact same query laravel logs in any MySQL client, the row gets inserted. So, what's going on??

If everything is ok using mySQL client you should see what's the difference between your SQL statement and the Laravel's.

$queries = DB::getQueryLog();
$last_query = end($queries);

checks what Laravel executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM