简体   繁体   English

在查询中使用AND的Laravel查询生成器

[英]Laravel query builder with AND in query

I want to add an "AND" clause to the end of a query builder, the code looks like this: 我想在查询构建器的末尾添加一个“AND”子句,代码如下所示:

$orderers = DB::table('address')->where(function($query) use ($term) {
                            $query->where('id', 'LIKE', '%' . $term . '%')
                                    ->or_where('name', 'LIKE', '%' . $term . '%')
                                    ->or_where('status', 'LIKE', '%' . $term . '%')
                                    ->and_clause_goes_here('is_orderer', '=', '1');
                        })->paginate($per_page);

But searching for a AND clause in Laravel I couldn't find any of equivalent. 但是在Laravel中搜索AND条款我找不到任何等价物。 Could you help me with this problem? 你能帮我解决这个问题吗?

JCS solution may still yield some unexpected results due to the order of operations. 由于操作顺序,JCS解决方案仍可能产生一些意外结果。 You should group all the OR's together as you would in SQL, explicitly defining the logic. 您应该像在SQL中一样将所有OR组合在一起,明确定义逻辑。 It also makes it easier to understand for the next time you ( or to another team member ), when they read the code. 它还使您在下次(或其他团队成员)阅读代码时更容易理解。

SELECT * FROM foo WHERE a = 'a' 
AND (
    WHERE b = 'b'
    OR WHERE c = 'c'
)
AND WHERE d = 'd'


Foo::where( 'a', '=', 'a' )
    ->where( function ( $query )
    {
        $query->where( 'b', '=', 'b' )
            ->or_where( 'c', '=', 'c' );
    })
    ->where( 'd', '=', 'd' )
    ->get();

simply another where clause will do, AND will be use 只是另一个where子句会做,AND将被使用

$orderers = DB::table('address')->where(function($query) use ($term) {
                            $query->where('id', 'LIKE', '%' . $term . '%')
                                    ->where('is_orderer', '=', '1');
                                    ->or_where('name', 'LIKE', '%' . $term . '%')
                                    ->or_where('status', 'LIKE', '%' . $term . '%')
                        })->paginate($per_page);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM