【问题标题】:Cannot use mysql function IN in laravel db statement无法在 laravel db 语句中使用 mysql 函数 IN
【发布时间】:2016-05-23 16:56:06
【问题描述】:

在 Laravel 5.2 DB 语句中使用 MySQL 的 IN 函数时遇到问题。示例如下:

$str_array = implode(",",$array_reservations);
$sql_result = DB::select("
            select r.id,r.people,r.date,r.status,p.alias,u.name,p.profile
            from  reservations r inner join places p on p.id = r.place_id 
            inner join  users u on u.id = r.user_id
            where r.id in(?)
            order by r.date desc
            ", [$str_array]);

但是在结果中我只是得到了数组第一次保留的结果。

数组的长度总是可变的。

【问题讨论】:

  • 你试过DB::raw($query);吗??
  • 就像@P.Gearman 指出的那样;参考:stackoverflow.com/questions/26465243/…
  • 您不能对整个 IN 列表使用单个绑定占位符,您必须为每个元素使用单独的占位符,并将 $array_reservations 作为数组传递,而不是作为逗号分隔的字符串

标签: php mysql laravel laravel-5


【解决方案1】:

在这种情况下,您需要使用 DB::raw。此外,您需要创建尽可能多的“?”您需要,对于您要绑定的每个 id。这就是 PDO 的工作方式:

$str_array = implode(",",$array_reservations);
$bindings = trim(str_repeat('?,', count($array_reservations)), ',');

DB::select($sql, $inputids);
$sql_result = DB::select(DB::raw("
        select r.id,r.people,r.date,r.status,p.alias,u.name,p.profile
        from  reservations r inner join places p on p.id = r.place_id 
        inner join  users u on u.id = r.user_id
        where r.id in($bindings)
        order by r.date desc
        "), $str_array);

但是,IMO,您应该使用查询生成器:

DB::table('reservations')
    ->join('places','places.id','=','reservarions.place_id')
    ->join('users','users.id','=','reservarions.user__id')
    ->whereIn('reservations.id',$str_array)
    ->orderBy('reservations.date', 'DESC');

【讨论】:

    【解决方案2】:

    试试这个:

      $sql_result = DB::table('reservations AS r')
            ->join('places AS p', 'p.id', '=', 'r.place_id')
            ->join('users AS u', 'u.id', '=', 'r.user_id')
            ->select('r.id','r.people','r.date','r.status','p.alias','u.name','p.profile')
            ->whereIn('r.id',$str_array)                    // write you conditions in array
            ->orderBy('r.date', 'desc')
            ->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-08
      • 2011-04-03
      • 2020-06-20
      • 2011-01-12
      • 2017-11-01
      • 1970-01-01
      • 2014-04-18
      • 2019-12-19
      相关资源
      最近更新 更多