Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove one to many relationship with Laravel 5

I have one to many relationship

In my Task controller

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

In my Todo controller

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

Adding the relationship with the following code

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

but i want to delete it later not the object just the relationship

any ideas

like image 955
sger Avatar asked Jul 23 '15 14:07

sger


2 Answers

In this chapter of the docs:

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

So in your case,

$task->todo()->dissociate();
$task->save();
like image 71
littlegreen Avatar answered Sep 26 '22 04:09

littlegreen


Assuming a normal schema, you'll have a todo_id column on your tasks table. Unset it for the record you want to detach.

$task->todo_id = null;
$task->save();
like image 43
deefour Avatar answered Sep 26 '22 04:09

deefour