PHP - Laravel:Raw Sql Query在控制器中显示错误

时间:2016-05-15 08:21:52

标签: php mysql laravel laravel-5

我正在构建一个laravel应用程序,我必须生成一个报告,因为我已经构建了一个控制器,并且我已经编写了一个查询来生成该报告,但它显示了以下错误。

  

RoomController.php中的FatalErrorException:语法错误,   意外的'R'(T_STRING)

问题在于R No不是数据库但是要在报告中显示我必须使用我已经汇总的行值。 我该如何解决这个问题?

public function ajax_view_schedule(Request $request)
    {
        $dept_id=$request->get(['dept_id']);
$schedule= DB::select(DB::raw('SELECT courses.code as c_code, courses.name as c_name,COALESCE( CONCAT('R. No',':',rooms.room_number,', ',days.name ,', ', allocate_rooms.start,' - ',allocate_rooms.end),"Not Scheduled Yet") AS Schedule 
FROM departments join courses on departments.id = courses.department_id
left join allocate_rooms on allocate_rooms.course_id=courses.id 
left join rooms on allocate_rooms.room_id=rooms.id
left join days on allocate_rooms.day_id=days.id WHERE departments.id='.$dept_id.''));
        return \Response::json($course);  
    }

2 个答案:

答案 0 :(得分:1)

错误指向此部分:

CONCAT('R. No',':',rooms.room_number,', ',days.name ,', ', allocate_rooms.start,' - ',allocate_rooms.end)

看看'R. No

你不能把字符串放在引号之外,希望php能理解如何处理它, 如果你想把引号放在引号内,你需要逃避它们, Escaping quotation marks in PHP

答案 1 :(得分:1)

尝试在SQL查询中使用双引号和单引号引用PHP字符串。

因此,您的查询字符串将如下所示:

$schedule= DB::select(DB::raw("SELECT courses.code as c_code, courses.name as c_name,COALESCE( CONCAT('R. No',':',rooms.room_number,', ',days.name ,', ', allocate_rooms.start,' - ',allocate_rooms.end),'Not Scheduled Yet') AS Schedule 
FROM departments join courses on departments.id = courses.department_id
left join allocate_rooms on allocate_rooms.course_id=courses.id 
left join rooms on allocate_rooms.room_id=rooms.id
left join days on allocate_rooms.day_id=days.id WHERE departments.id='.$dept_id.'"));