能否将detach()方法应用于Laravel中的一对多关系? [英] can detach() method also be applied to one to many relationship in Laravel?
问题描述
在Laravel文档中,我找到了detach()方法来分离所有对象之间的多对多关系.能否将detach()方法也应用于Laravel中的一对多关系?如果没有,在这种情况下如何分离所有n个对象?
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?
推荐答案
在多对多关系中,除非您具有特定的级联删除功能,否则detach()方法仅删除数据库中的数据透视表条目.
In many to many relationships, detach() method only delete pivot entry in your database, except if you have specific cascade deleting.
对于一对多关系,您想使用dissociate()方法解除该关系的绑定,并使用associate()将其绑定到belongsTo Side.
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);
相反,您可以在hasMany端使用attach()添加帐户:
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();
更多信息在这里: https://laravel.com/docs/5.6/eloquent-relationships
这篇关于能否将detach()方法应用于Laravel中的一对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!