【发布时间】:2019-02-24 14:41:55
【问题描述】:
我的应用程序有一个Category 模型。每个Category 可以有多个Subcategories,所以每个Subcategory belongsTo 一个Category。来自Subcategory 模型:
public function category()
{
return $this->belongsTo('App\Category');
}
另一方面,有一个Friend 模型。现在,每个 Friend/Subcategory 对都通过枢轴 friend_score 表连接:
id | friend_id | subcategory_id | score
来自Subcategory 模型:
/**
* The friend scores that belong to the subcategory.
*/
public function friends()
{
return $this->belongsToMany('App\Friend', 'friend_score')->withPivot('score');
}
来自Friend 模型:
/**
* The subcategory scores that belong to the friend.
*/
public function subcategories()
{
return $this->belongsToMany('App\Subcategory', 'friend_score')->withPivot('score');
}
当我删除一个子类别时,Eloquent 会自动且正确地从friend_score 表中删除该subcategory_id 的条目。
当我删除一个类别时,它会正确删除属于该category_id 的子类别。但是,在这种情况下,相关的friend_scores 仍保留在数据库中。
删除类别时如何使其删除每个子子类别的friend_score?
我知道我可以手动遍历它们并删除它们,但我想知道是否有办法通过模型关系自动实现这一点。
【问题讨论】:
-
你能显示子类别表结构吗?
-
@TeomanTıngır 这只是
id | category_id | name | created_at | updated_at