我正在尝试使用Eloquent创建这样的东西。但是,我遇到了or子句的问题。
SELECT * FROM table WHERE column1 = 1 AND column2 = 2 AND (column3 LIKE $search_term.'%' OR column4 LIKE $search_term.'%') ORDER BY column1;
这就是我所拥有的:
$query = DB::table('table')
->where('column1', '=', 1)
->where('column2', '=', 2)
->orderBy('column1', 'asc');
$results = App\Table::where(function ($query) use ($search_term) {
$query->where('column3', 'like', $search_term.'%');
})->orwhere(function ($query) use ($search_term) {
$query->where('column4', 'like', $search_term.'%');
});
答案 0 :(得分:5)
您的查询应如下所示:
$query = DB::table('table')
->where('column1', 1)
->where('column2', 2)
->where(function ($q) use ($search_term) {
$q->where('column3', 'like', $search_term.'%')
->orWhere('column4', 'like', $search_term.'%');
})
->orderBy('column1', 'asc')
->get();
答案 1 :(得分:1)
您也可以使用whereRaw
子句:
App\Table::where('column1', 1)
->where('column2', 2)
->whereRaw("(column3 LIKE $search_term.'%' OR column4 LIKE $search_term.'%')")
->orderBy('column1', 'asc');
答案 2 :(得分:0)
$results = App\Table::select('*')
->where('column1', 1)
->where('column2', 2)
->where(function ($query) use ($search_term) {
$query->where('column3', 'like', $search_term.'%')
->orWhere('column4', 'like', $search_term.'%')
})
->orderBy('column1', 'asc')
->get();