【问题标题】:Unable to pass multiple values in not like clause Laravel无法在 not like 子句 Laravel 中传递多个值
【发布时间】:2017-05-07 16:35:20
【问题描述】:

我正在做一个 Laravel 项目,想在 not like 子句中发布多个值。我尝试了以下方法,但没有成功。

    $exclude_emails=['odz', 'test.com'];

    $vendors=\DB::table("vendor_infos")
              ->where("vendor_infos.email", 'not like', '%'.$exclude_emails.'%' )
              ->orderByRaw("RAND()")->take(8)->get(['vendor_infos.*']);

我也尝试过将它作为字符串传递,但仍然没有成功。

【问题讨论】:

    标签: php laravel-5.1 laravel-query-builder


    【解决方案1】:

    你可以这样做,

    $query = DB::table("vendor_infos");
    foreach($exclude_email as $v){
     $query->where("vendor_infos.email",'not like','%'.$v.'%');
    }
    $vendors = $query->orderByRaw("RAND()")->take(8)->get(['vendor_infos.*']);
    

    我希望这会奏效

    编辑

    或者你可以尝试其他方式。

    $exclude_emails = [
     ['vendor_infos.email' ,'not like','%'.'odz'.'%'],
     ['vendor_infos.email' ,'not like','%'.'test.com'.'%'],
    ];
     $vendors=\DB::table("vendor_infos")
                  ->where($exclude_emails)
                  ->orderByRaw("RAND()")->take(8)->get(['vendor_infos.*']);    
    

    【讨论】:

      【解决方案2】:

      为什么不使用自定义查询!

       $exclude_emails=['%odz%', '%test.com%'];
       $exclude_emails = implode('|', $exclude_emails);
       SELECT * FROM  `vendor_infos` WHERE `email` NOT REGEXP '{$exclude_emails}' . . .
      

      简单,不管$exclude_emails的大小。

      Laravel 方式:

      如果你坚持用 laravel 这样做,你可以这样做:

      // making conditions array
      foreach($exclude_emails as $e){
        $final_conditions[] = ['email', 'not like', $e];
      }
      

      @AmitGupta 回答的查询:

      DB::table("vendor_infos")->where( $final_conditions)->orderByRaw("RAND()")->take(8)->get();
      

      【讨论】:

        【解决方案3】:

        您不能在由撇号包裹的字符串中使用数组。 where 函数的第三个参数中已经有 '%' 字符。你为什么在你的字符串中再次使用?

        试试这个:

         $vendors=\DB::table("vendor_infos")
                  ->where("vendor_infos.email", 'not like', '%odz%')
                  ->where("vendor_infos.email", 'not like', '%test.com%')
                  ->orderByRaw("RAND()")->take(8)->get(['vendor_infos.*']);
        

        【讨论】:

          猜你喜欢
          • 2020-11-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-11
          • 1970-01-01
          • 1970-01-01
          • 2023-01-18
          相关资源
          最近更新 更多