在中间表上进行软删除以实现多对多关系 [英] Soft delete on a intermediate table for many-to-many relationship
本文介绍了在中间表上进行软删除以实现多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在连接两种不同类型实体的中间表上设置软删除?我添加了delete_at列,但是文档说我需要将其放入模型中:
How do I set soft delete on an intermediate table which is connecting two different types of entities? I've added deleted_at column, but the docs say that I need to put this into the model:
protected $softDelete = true;
当然,我没有中间表的模型. 有什么主意吗?
Of course, I don't have a model for an intermediate table. Any idea?
推荐答案
您可以对急切负载施加约束:
You can put a constraint on the Eager Load:
public function groups()
{
return $this
->belongsToMany('Group')
->whereNull('group_user.deleted_at') // Table `group_user` has column `deleted_at`
->withTimestamps(); // Table `group_user` has columns: `created_at`, `updated_at`
}
使用以下方法代替HARD删除关系:
Instead of HARD deleting the relationship using:
User::find(1)->groups()->detach();
您应该使用类似这样的方式来SOFT Delete:
You should use something like this to SOFT delete instead:
DB::table('group_user')
->where('user_id', $user_id)
->where('group_id', $group_id)
->update(array('deleted_at' => DB::raw('NOW()')));
这篇关于在中间表上进行软删除以实现多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文