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

首页,说一下我的业务场景,有三张表,分别为floors表用于记录楼层信息,goods表记录商品信息,floor_goods表记录楼层和商品的对应关系。这样的话,floor_goods为中间表,正常进行关联查询没有问题,但是我将floor_goods中的某一条数据进行了软删除后,然后进行查询,还是能够找到该条数据,我应该怎么样才能过滤掉已被删除的数据?希望得到解答,谢谢!

Hesunfly
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

方法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`
}
5年前 评论
讨论数量: 2

方法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`
}
5年前 评论
Hesunfly

多谢您的回答,我试了一下,第二个方式,可以解决我的问题,多谢!第一个方式我在之前试过,直接抛出了异常,再次感谢您的解答!

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!