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

2019-09-19 13:03发布

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?

2条回答
来,给爷笑一个
2楼-- · 2019-09-19 13:13

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

查看更多
Fickle 薄情
3楼-- · 2019-09-19 13:13

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();
查看更多
登录 后发表回答