我尝试从具有多个 where 和/或子句的表中获取结果。
我的 SQL 语句是:
SELECT * FROM tbl
WHERE m__Id = 46
AND
t_Id = 2
AND
(Cab = 2 OR Cab = 4)
我怎样才能用 Laravel Eloquent 得到这个?
我在 Laravel 中的代码是:
$BType = CabRes::where('m_Id', '=', '46')
->where('t_Id', '=', '2')
->where('Cab', '2')
->orWhere('Cab', '=', '4')
->get();
使用 advanced wheres:
CabRes::where('m__Id', 46)
->where('t_Id', 2)
->where(function($q) {
$q->where('Cab', 2)
->orWhere('Cab', 4);
})
->get();
或者,更好的是,使用 whereIn()
:
CabRes::where('m__Id', 46)
->where('t_Id', 2)
->whereIn('Cab', $cabIds)
->get();
另外,如果你有一个变量,
CabRes::where('m_Id', 46)
->where('t_Id', 2)
->where(function($q) use ($variable){
$q->where('Cab', 2)
->orWhere('Cab', $variable);
})
->get();
当我们将多个 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();
上面的查询验证所有 where 条件,然后最后检查 where t2.status=1 和 (where t2.contact_users_id='$userid' or where t1.users_id='$userid')
您可以尝试改用以下代码:
$pro= model_name::where('col_name', '=', 'value')->get();
$cabIds
来自哪里?