删除Laravel 5的一对多关系


Remove one to many relationship with Laravel 5

我有一对多关系

在我的任务控制器

public function todo()
{
  return $this->belongsTo('App'Todo');
}

我的Todo控制器

public function tasks()
{
  return $this->hasMany('App'Task');
}

用以下代码添加关系

$todo = new Todo
$todo->save();
$task = new Task
$todo->tasks()->save($task);
$task->save();

但我想稍后删除它不是对象而是关系

任何想法

在本章的文档中:

When removing a belongsTo relationship, you may use the dissociate method. 
This method will reset the foreign key as well as the relation on the child model:
$user->account()->dissociate();
$user->save();

在你的例子中,

$task->todo()->dissociate();
$task->save();

假设是一个正常的模式,您将在tasks表上有一个todo_id列。为要分离的记录取消设置。

$task->todo_id = null;
$task->save();