【发布时间】:2015-09-26 17:31:51
【问题描述】:
我有 2 个模型,它们由具有复合键的关系连接 - 它们是产品和类别。我需要对所有表使用软删除,以便在需要时恢复模型和关系。
在我的产品模型中,我有:
function categories()
{
return $this->belongsToMany('App\Category', 'product_categories')->whereNull('product_categories.deleted_at')->withTimestamps();
}
在我的类别模型中,我有:
function products()
{
return $this->belongsToMany('App\Product', 'product_categories')->whereNull('product_categories.deleted_at')->withTimestamps();
}
我在其他地方读到了有关链接 whereNull 方法的信息,因为像 $category->products->contains($product->id) 这样的查询会返回软删除的关系。
我的问题是处理删除和恢复这些软删除关系的最佳方法是什么?例如,为了恢复,我尝试了:
$product->categories()->restore($category_id);
上面产生了一个 SQL 错误,指出 deleted_at 字段不明确(因为它将类别表连接到 product_categories)。
更新 - 根本问题似乎是 BelongsToMany 类不支持软删除 - 所以附加、分离和同步都执行硬删除。覆盖此类的最佳方法是什么?
【问题讨论】: