简体   繁体   English

Laravel MySQL无法在可以为空的外键中插入null

[英]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: 我正在使用Laravel 4.2开发一个应用程序,其中我有一个像这样创建的表:

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: 两列都可以为null但是当我插入这样的内容时:

$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 我收到MySQL错误告诉我: 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. 但是如果我在任何MySQL客户端中运行完全相同的查询laravel日志,则会插入该行。 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. 如果使用mySQL客户端一切正常,你应该看到你的SQL语句和Laravel之间有什么区别。

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

checks what Laravel executed. 检查Laravel执行的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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