在laravel db语句中不能使用mysql函数IN

时间:2016-05-23 16:56:07

标签: php mysql laravel laravel-5

在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]);

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

数组的长度总是可变的。

2 个答案:

答案 0 :(得分: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,你应该使用Query Builder:

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');

答案 1 :(得分:1)

试试这个:

  $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();