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