15

我想在查询生成器的末尾添加一个“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);

但是在 Laravel 中搜索 AND 子句我找不到任何等价物。你能帮我解决这个问题吗?

4

2 回答 2

30

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.

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();
于 2013-03-08T19:10:46.633 回答
16

只需另一个 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);
于 2013-03-08T03:18:43.307 回答