[英]Laravel 5 Null Foreign Key Error
我搜索了一会儿,找不到解决此问题的方法。 我在todo_items表中有一个自引用外键
Schema::create('todo_items', function(Blueprint $table)
{
//....
$table->integer('todo_list_id')->unsigned();
//Added default(null) to see if it would help
$table->integer('parent_id')->unsigned()->nullable()->default(null);
//......
});
Schema::table('todo_items',function($table)
{
$table->foreign('parent_id')
->references('id')
->on('todo_items')
->onDelete('cascade')
->onUpdate('cascade');
}
也有一个变种器
public function setParentIdAttribute($value){
$this->attributes['parent_id'] = $value ?: null;
}
但是,当我尝试将TodoItem模型存储在具有null parent_id的数据库中时,它给了我这个错误
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ('todo_manager'.'todo_items', CONSTRAINT 'todo_items_parent_id_foreign' FOREIGN KEY ('parent_id') REFERENCES 'todo_items' ('id') ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into 'todo_items' ('content', 'parent_id', 'todo_list_id', 'updated_at', 'created_at') values (sadsdasd, null, 1, 2015-05-13 11:38:50, 2015-05-13 11:38:50))
public function store(TodoList $list,CreateTodoItemRequest $request)
{
$item = new TodoItem($request->all());
$list->items()->save($item);
//never reaches here
dd($item);
return redirect()->route('lists.show',[$list]);
}
想知道我将如何解决这个问题
找出问题所在。 显然null被存储为一个字符串(不完全确定为什么有人可以帮助它),但是更改了mutator,这有点hacky ...但是现在可以使用
public function setParentIdAttribute($value){
$this->attributes['parent_id'] = $value == "null" ? null : $value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.