php Laravel 查询构建器在查询中使用 AND
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15285892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel query builder with AND in query
提问by petwho
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. Could you help me with this problem?
但是在 Laravel 中搜索 AND 子句我找不到任何等效项。你能帮我解决这个问题吗?
回答by Collin James
JCS solution may still yield some unexpected results due to the order of operations. You should group all the OR's together as you would in SQL, explicitly defining the logic. It also makes it easier to understand for the next time you ( or to another team member ), when they read the code.
由于操作顺序的原因,JCS 解决方案仍然可能会产生一些意想不到的结果。您应该像在 SQL 中一样将所有 OR 组合在一起,明确定义逻辑。它还可以让您(或其他团队成员)下次阅读代码时更容易理解。
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();
回答by jcs
simply another where clause will do, AND will be use
只需另一个 where 子句即可,并且将使用
$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);

