SQL Laravel 5 Eloquent where 和 or in 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30434037/
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 5 Eloquent where and or in Clauses
提问by Crni
i try to get results from table with multiple where and/or clauses.
我尝试从包含多个 where 和/或子句的表中获取结果。
My SQL statement is:
我的 SQL 语句是:
SELECT * FROM tbl
WHERE m__Id = 46
AND
t_Id = 2
AND
(Cab = 2 OR Cab = 4)
How i can get this with Laravel Eloquent?
我怎么能用 Laravel Eloquent 得到这个?
My Code in Laravel is:
我在 Laravel 中的代码是:
$BType = CabRes::where('m_Id', '=', '46')
->where('t_Id', '=', '2')
->where('Cab', '2')
->orWhere('Cab', '=', '4')
->get();
回答by Limon Monte
Using advanced wheres:
使用高级 wheres:
CabRes::where('m__Id', 46)
->where('t_Id', 2)
->where(function($q) {
$q->where('Cab', 2)
->orWhere('Cab', 4);
})
->get();
Or, even better, using whereIn()
:
或者,更好的是,使用whereIn()
:
CabRes::where('m__Id', 46)
->where('t_Id', 2)
->whereIn('Cab', $cabIds)
->get();
回答by Jaber Al Nahian
Also, if you have a variable,
另外,如果你有一个变量,
CabRes::where('m_Id', 46)
->where('t_Id', 2)
->where(function($q) use ($variable){
$q->where('Cab', 2)
->orWhere('Cab', $variable);
})
->get();
回答by Hemamalini
When we use multiple and
(where) condition with last (where + or where) the where condition fails most of the time. for that we can use the nested where function with parameters passing in that.
当我们使用多个and
(where) 条件和 last (where + 或 where) 时,where 条件大部分时间都失败了。为此,我们可以使用带有参数传入的嵌套 where 函数。
$feedsql = DB::table('feeds as t1')
->leftjoin('groups as t2', 't1.groups_id', '=', 't2.id')
->where('t2.status', 1)
->whereRaw("t1.published_on <= NOW()")
>whereIn('t1.groupid', $group_ids)
->where(function($q)use ($userid) {
$q->where('t2.contact_users_id', $userid)
->orWhere('t1.users_id', $userid);
})
->orderBy('t1.published_on', 'desc')->get();
The above query validate all where condition then finally checks where t2.status=1 and (where t2.contact_users_id='$userid' or where t1.users_id='$userid')
上面的查询验证所有 where 条件然后最后检查 where t2.status=1 and (where t2.contact_users_id='$userid' or where t1.users_id='$userid')
回答by souvik gain
You can try to use the following code instead:
您可以尝试改用以下代码:
$pro= model_name::where('col_name', '=', 'value')->get();