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

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

Hesunfly
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 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年前 评论

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