我已经搜索了一段时间,无法找到解决此问题的方法。 我在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');
}
还有一个mutator
public function setParentIdAttribute($value){
$this->attributes['parent_id'] = $value ?: null;
}
但是,当我尝试使用null parent_id在db中存储TodoItem模型时,它会给我这个错误
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]);
}
想知道如何解决这个问题
答案 0 :(得分:2)
找出问题所在。显然null被存储为一个字符串(不完全确定为什么如果有人可以提供帮助)但改变了mutator并且它有点hacky ......但它现在有效
public function setParentIdAttribute($value){
$this->attributes['parent_id'] = $value == "null" ? null : $value;
}