can detach() method also be applied to one to many

2019-09-19 12:34发布

问题:

in Laravel documentation i found detach() method to detach all objects in many to many relationships. Can detach() method also be applied to one to many relationship in Laravel? if not, how can I detach all n objects in this case?

回答1:

In many to many relationships, detach() method only delete pivot entry in your database, except if you have specific cascade deleting.

For one to many relationship, you want to use dissociate() method to unbind the relation and associate() to bind it on the belongsTo Side.

    $comment->post()->associate($post->id);

On the contrary, you would add account using attach() on the hasMany side:

    $post->comments()->attach($comment->id);

To delete all comments you would do :

    $post->comments()->delete();

More info here: https://laravel.com/docs/5.6/eloquent-relationships



回答2:

From the docs

When removing a belongsTo relationship, you may use the dissociate method. This method will set the relationship's foreign key to null

$user->account()->dissociate();

$user->save();