简体   繁体   中英

Laravel 5 Null Foreign Key Error

I've searched around for awhile and couldn't find a solution to this problem. I have a self referencing foreign key in a todo_items table

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

Also have a mutator

public function setParentIdAttribute($value){
        $this->attributes['parent_id'] = $value ?: null;
    }

However when I attempt to store a TodoItem model in the db with a null parent_id it gives me this error

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))

Controller Store Method

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

Was wondering how I would go about fixing this

Figured out the problem. Apparently null was being stored as a string (not entirely sure why if anyone can help with that) but altered the mutator and it's sort of hacky...but it works for now

public function setParentIdAttribute($value){
        $this->attributes['parent_id'] = $value == "null" ? null : $value;
}

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