【问题标题】:Laravel 5 Eloquent where and or in ClausesLaravel 5 Eloquent where 和 or in 子句
【发布时间】:2015-08-06 16:19:57
【问题描述】:

我尝试从包含多个 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();

【问题讨论】:

    标签: sql laravel eloquent


    【解决方案1】:

    使用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();
    

    【讨论】:

    • 谢谢你,这是有效的 :) 但是如果我的数组喜欢,我怎么能用 cab 数组获得这个:arrCab[2,4,6]
    • 为什么更好,变量$cabIds从哪里来?
    • 第二个选项最好
    • 我可以请你看看这里的 Laravel 表连接相关问题:stackoverflow.com/questions/52149031/…?
    【解决方案2】:

    另外,如果你有一个变量,

    CabRes::where('m_Id', 46)
          ->where('t_Id', 2)
          ->where(function($q) use ($variable){
              $q->where('Cab', 2)
                ->orWhere('Cab', $variable);
          })
          ->get();
    

    【讨论】:

    【解决方案3】:

    当我们使用多个 and (where) 条件和 last (where + or 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 条件然后最后检查 其中 t2.status=1 和 (其中 t2.contact_users_id='$userid' 或 t1.users_id='$userid')

    【讨论】:

      【解决方案4】:

      您可以尝试使用以下代码:

       $pro= model_name::where('col_name', '=', 'value')->get();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-28
        • 2013-06-04
        • 2016-06-13
        • 2016-10-23
        • 1970-01-01
        相关资源
        最近更新 更多