【问题标题】:Nested orwhere in one where - Laravel嵌套在一个地方 - Laravel
【发布时间】:2020-03-06 07:32:35
【问题描述】:

我需要在 Laravel 6 中构建一个查询,该查询将 where's 嵌套在一个 where 查询中。 例如: Select * FROM example where k=5 and ((i=1 and j=2) or (i=3 and j=4) or (i=5 and j=4)......)

我试过下面的代码

                $getItems = $getItems->where(function ($query) use($codes,$cID) {
                        $query->orWhere(function ($query1) use ($codes, $cID) {
                            foreach($codes[$cID] as $code) {
                                $query1
                                    ->where('code', $code)
                                    ->where('cid', $cID);
                            }
                        });
                });

但结果是错误的。

and (("code" = ? and "cid" = ?)) and (("code" = ? and "cid" = ?)) and (("code" = ? and "cid" = ?))....

我不明白为什么它在每个 foreach 循环中添加 2 个括号,以及为什么它添加“and”而不是“or”。 关于如何构建它的任何建议?

【问题讨论】:

标签: laravel where-clause


【解决方案1】:

你应该有这样的结构:

Model::where('k', 5)->where(function($q){
        $q->orWhere(function($q){
            $q->where('i', 1)->where('j', 2);
        })->orWhere(function($q){
            $q->where('i', 3)->where('j', 4);
        })->orWhere(function($q){
            $q->where('i', 5)->where('j', 4);
        });
    })->toSql();

> select * from `table` where `k` = ? and ((`i` = ? and `j` = ?) or (`i` = ? and `j` = ?) or (`i` = ? and `j` = ?))

所以你的查询应该是:

$getItems->where('k', 5)
    ->where(function ($query) use($codes, $cID) {
        foreach($codes[$cID] as $code) {
            $query->orWhere(function ($query1) use ($code, $cID) {
                $query1->where('code', $code)->where('cid', $cID);
            });
        }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-02
    • 2010-10-06
    • 2013-02-14
    • 1970-01-01
    • 2018-06-07
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多