讨论数量:
不建议对pivot进行软删除, 有没有觉得这样做逻辑会很乱?
你可以在pivot上添加一个字段, 比如is_deleted
, updateExistingPivot()
可以修改这个字段, wherePivot('is_deleted', true)
可以筛选数据.
\App\Book::find(1)->buyers()->wherePivot('is_deleted', true)->get()
\App\Book::find(1)->buyers()->updateExistingPivot(11, ['is_deleted' => false])
或者在关系里面定义俩关系
function buyers() {
return $this->belongToMany('App\User')->wherePivot('is_deleted', false);
}
function buyersWithDeleted() {
return $this->belongToMany('App\User');
}
可以考虑以下方法.
方法1:
用sync代替detach.
方法2:
修改关系类
首先继承和修改下BelongToMany类, detach函数在InteractsWithPivotTable这个trait里面可以找到.
接着在你需要的修改detach功能Model里面重写belongToMany()方法, 如果是L5.4可以再HasRelationships这个trait里面可以看到原始实现, L5.3直接在Model.php里面可以看到
方法3:
在原始代码中修改detach函数
推荐文章: