使用模型关联多不多关系查找数据,关联数据在中间表已经软删除,但是数据还是查找出来了,怎么解决呢?

weixin_38067509 2019-09-18 04:04:58
首页,说一下我的业务场景,有三张表,分别为floors表用于记录楼层信息,goods表记录商品信息,floor_goods表记录楼层和商品的对应关系。这样的话,floor_goods为中间表,正常进行关联查询没有问题,但是我将floor_goods中的某一条数据进行了软删除后,然后进行查询,还是能够找到该条数据,我应该怎么样才能过滤掉已被删除的数据?希望得到解答,谢谢! eloquent database
...全文
124 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38090274 2019-09-18
  • 打赏
  • 举报
回复
多谢您的回答,我试了一下,第二个方式,可以解决我的问题,多谢!第一个方式我在之前试过,直接抛出了异常,再次感谢您的解答!
weixin_38067950 2019-09-18
  • 打赏
  • 举报
回复
方法1: 根据文档: 通过中间表列过滤关系 在定义关系时,你还可以使用 wherePivot 和 wherePivotIn 方法来过滤 belongsToMany 返回的结果: return $this->belongsToMany('App\Role')->wherePivot('approved', 1); return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]); $member->positions()->wherePivot('deleted_at', '<>', null)->get(); // 过滤删除的 $member->positions()->wherePivot('deleted_at', null)->get(); // 软删除的 (测试时没有写在关联关系方法里,当然你可以直接写在多对多关联关系里面) 方法2: 还是给多对多关联关系添加条件 这是stackoverflow上某个回答:https://stackoverflow.com/questions/173500... 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` }
weixin_38076856 2019-09-18
  • 打赏
  • 举报
回复
方法1: 根据文档: 通过中间表列过滤关系 在定义关系时,你还可以使用 wherePivot 和 wherePivotIn 方法来过滤 belongsToMany 返回的结果: return $this->belongsToMany('App\Role')->wherePivot('approved', 1); return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]); $member->positions()->wherePivot('deleted_at', '<>', null)->get(); // 过滤删除的 $member->positions()->wherePivot('deleted_at', null)->get(); // 软删除的 (测试时没有写在关联关系方法里,当然你可以直接写在多对多关联关系里面) 方法2: 还是给多对多关联关系添加条件 这是stackoverflow上某个回答:https://stackoverflow.com/questions/173500... 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` }

433

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧