gpt4 book ai didi

php - Laravel 5 空外键错误

转载 作者:太空宇宙 更新时间:2023-11-03 11:59:31 26 4
gpt4 key购买 nike

我搜索了一段时间,没有找到解决这个问题的办法。我在 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;
}

但是,当我尝试使用空 parent_id 在数据库中存储 TodoItem 模型时,出现此错误

SQLSTATE[23000]:违反完整性约束:1452 无法添加或更新子行:外键约束失败('todo_manager'.'todo_items',CONSTRAINT 'todo_items_parent_id_foreign' FOREIGN KEY('parent_id')引用'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))

Controller 存储方法

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;
}

关于php - Laravel 5 空外键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30219714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com