我正在构建一个laravel控制器,我试图避免时间重叠。但是由于我无法在我的控制器中正确运行查询,因此我的查询存在问题:
public function postAllocateRoom(Request $request)
{
$classRoom = new ClassRoom();
$classRoom->department_id=$request->Input(['department_id']);
$classRoom->room_id=$request->Input(['room_id']);
$classRoom->course_id=$request->Input(['course_id']);
$classRoom->day_id=$request->Input(['day_id']);
$classRoom->start=Carbon::parse(str_replace(array('am', 'pm'), ':00', $request->input('start')));
$classRoom->end=Carbon::parse(str_replace(array('am', 'pm'), ':00', $request->input('end')));
$day = $classRoom->day_id;
$startTime=$classRoom->start;
$endTime=$classRoom->end;
$result=DB::select( DB::raw("SELECT * FROM `allocate_rooms`
WHERE start='$startTime' AND end='$endTime' AND day_id='day'"));
if (sizeof($result)>0) {
flash()->error('Class Room Already Taken.');
return redirect('allocateRoomPage');
}
else {
$classRoom->save();
flash()->success('Successfully allocated room.');
return redirect('allocateRoomPage');
}
}
这里在我的控制器的查询中首先我将检查day_id是否已作为输入与该day_id与数据库匹配然后它将检查时间,如果匹配则结果将是多于一个,所以它可以' t让用户保存输入,否则如果查询失败,它将允许用户保存数据。
我遇到查询问题。如果有人帮助找出解决方案。
答案 0 :(得分:1)
首先,我建议您在创建模型实例之前对输入执行一些validations。
然后,我不明白为什么有时候使用$request->Input(['input_name'])
,有时使用$request->input('input_name')
,最好使用第二种语法。
我编辑了你的代码,请测试它,它应该可以工作。
public function postAllocateRoom(Request $request)
{
// SOME VALIDATION HERE BEFORE GO ON, PLEASE
$startTime = Carbon::parse(str_replace(array('am', 'pm'), ':00', $request->input('start')));
$endTime = Carbon::parse(str_replace(array('am', 'pm'), ':00', $request->input('end')));
$dayId = $request->input('day_id');
$timeExists = AllocateRooms::where('day_id', $dayId)
->where('start', $startTime)
->where('end', $endTime)
->exists(); //use allocate_rooms table model (I don't know if it is ClassRomm)
if($timeExists){
reuturn redirect('allocateRoomPage')->withErrors(['time' => 'Class Room Already Taken']);
}
$classRoom = new ClassRoom();
$classRoom->department_id=$request->input('department_id');
$classRoom->room_id=$request->input('room_id');
$classRoom->course_id=$request->input('course_id');
$classRoom->day_id=$dayId;
$classRoom->start=$startTime;
$classRoom->end=$endTime;
$classRoom->save();
$request->session()->flash('success', 'Successfully allocated room');
return redirect('allocateRoomPage');
}