首页 > 解决方案 > 在 eloquent 中使用 [IF] 时无法存储不起作用

问题描述

当 [Booking] 中有数据时我需要存储,但不存储任何内容 [scan]

public function store(Request $request, $id){
    $event = event::findOrFail($id);
    $booking = booking::where('student_id',Auth::user()->student_id)
    ->where('name',Auth::user()->name)
    ->where('event_id',$event->id);
    if($booking!=NULL){
    $requestData = $request->all();
    scan::create($requestData);
    return redirect('event/' . $event->id .'/scan');
    return view('event.scan', compact('event','scan','booking'));
    }else{
    return redirect('event/' . $event->id .'/scan');
    }
}

但是当使用 $booking==null 时,它会存储任何无法在预订中签到的东西

标签: laraveleloquent

解决方案


Your query is incomplete. It lacks of any final query method like get(), first() or exists()

Also you have two return statements inside the if block. Only the first will be executed, the second one will be ignored.

The correct code should be like this:

public function store(Request $request, $id){
    $event = event::findOrFail($id);

    $booking = booking::where('student_id',Auth::user()->student_id)
    ->where('name',Auth::user()->name)
    ->where('event_id',$event->id)
    ->get(); // look this line

    if($booking!=NULL){
        $requestData = $request->all();
        scan::create($requestData);
        return redirect('event/' . $event->id .'/scan'); // I think this should not be here, right?
        return view('event.scan', compact('event','scan','booking')); // this is being ignored.
    }else{
        return redirect('event/' . $event->id .'/scan');
    }
}

推荐阅读