首页 > 解决方案 > 如何使用 wherePivot belongsToMany 关系添加多个条件

问题描述

我正在使用 Laravel 7。我有 3 张桌子

表格1

table_1_table_2

表_2

所以我想要的是获取表中连接到table_1 中我的对象的所有条目。

所以我这样做了:

public function table2() {
    return $this->belongsToMany(table_2,'table_1_table_2','id_table_1','id_table2')->withPivot(['value','hidden']);
}

效果很好。现在我只想要那些没有隐藏的人。所以我做了

public function table2NotHidden() {
    return $this->belongsToMany(table_2,'table_1_table_2','id_table_1','id_table2')->wherePivot('hidden',0)->withPivot(['value','hidden']);
}

效果很好期待我在哪里需要它们,hidden == 0但如果hidden == null

我尝试了一些类似的东西->where(function($query){...}) ->wherePivot(function($query){...})......但似乎没有任何效果。

标签: laravel

解决方案


您可以尝试嵌套在哪里:

 public function table2NotHidden() {
        return $this->belongsToMany('table_2','table_1_table_2','id_table_1','id_table2')->
        where(function($query){ $query->wherePivot('hidden',0)->orWherePivot('hidden',null);
        });
}

或者您可以使用@Dilip Hirapara 解决方案:

->wherePivotIn('hidden', [0, null]);


return $this->belongsToMany(table_2,'table_1_table_2','id_table_1','id_table2')->where(function ($q) {
                    $q->orWhereNull('table_1_table_2.hidden')
                      ->orWhere('table_1_table_2.hidden',0);
                })

推荐阅读