【问题标题】:How to use multiple OR,AND condition in Laravel queries如何在 Laravel 查询中使用多个 OR、AND 条件
【发布时间】:2017-09-09 07:42:58
【问题描述】:

我需要帮助在 laravel 中查询

我的自定义查询:(返回正确结果)

Select * FROM events WHERE status = 0 AND (type="public" or type = "private")

如何在 Laravel 中编写此查询。

Event::where('status' , 0)->where("type" , "private")->orWhere('type' , "public")->get();

但它也会返回所有状态不为 0 的公共事件。

我正在使用 Laravel 5.4

【问题讨论】:

    标签: php mysql laravel laravel-5.4


    【解决方案1】:

    将闭包传递给where()

    Event::where('status' , 0)
         ->where(function($q) {
             $q->where('type', 'private')
               ->orWhere('type', 'public');
         })
         ->get();
    

    https://laravel.com/docs/5.4/queries#parameter-grouping

    【讨论】:

      【解决方案2】:

      在你的情况下,你可以重写查询......

      select * FROM `events` WHERE `status` = 0 AND `type` IN ("public", "private");
      

      还有 Eloquent:

      $events = Event::where('status', 0)
          ->whereIn('type', ['public', 'private'])
          ->get();
      

      如果您想要分组 OR/AND,请使用闭包:

      $events = Event::where('status', 0)
          ->where(function($query) {
              $query->where('type', 'public')
                  ->orWhere('type', 'private');
          })->get();
      

      【讨论】:

        【解决方案3】:

        使用这个

        $event = Event::where('status' , 0);
        
        $event = $event->where("type" , "private")->orWhere('type' , "public")->get();
        

        或者这个

        Event::where('status' , 0)
             ->where(function($result) {
                 $result->where("type" , "private")
                   ->orWhere('type' , "public");
             })
             ->get();
        

        【讨论】:

          【解决方案4】:

          试试这个。它对我有用。

          $rand_word=Session::get('rand_word');
          $questions =DB::table('questions')
              ->where('word_id',$rand_word)
              ->where('lesson_id',$lesson_id)
              ->whereIn('type', ['sel_voice', 'listening'])
              ->get();
          

          【讨论】:

            猜你喜欢
            • 2023-03-27
            • 2016-12-29
            • 1970-01-01
            • 2016-12-26
            • 1970-01-01
            • 1970-01-01
            • 2013-01-11
            • 1970-01-01
            相关资源
            最近更新 更多