Laravel 一对多关系无效

Laravel One to Many Relationship not working

我正在做酒店预订系统的作业。我有一个 table 命名的预订和另一个 table 房间。我在它们之间做了一个一对多的关系我想 return 房间名称到主视图,但它总是显示 Trying to get 属性 of non-object。这是我的代码。 预订控制器类 GuestBookingController 扩展控制器

public function new()
{
    $rooms = Room::all();
    $guests = Guest::all();
    return view('guestbookings.new', compact('rooms','guests'));
}

public function store(Request $request)
{
    $validatedData = $request->validate([
        'checkin_dtime' => 'required',
        'checkout_dtime' => 'required',
        'id_number' => 'required|unique:guests',
        'mobile' => 'required',
         ]);

    $result = Booking::where('checkin_dtime', '<=',$request->checkin_dtime)->where('checkout_dtime', '>=',$request->checkout_dtime)->where('room_id',$request->room_id)->first();
   if(!$result){
   $bookings = new Booking;
   $bookings->checkin_dtime = $request->input('checkin_dtime');
   $bookings->checkout_dtime = $request->input('checkout_dtime');
   $bookings->user_id = auth()->user()->id;
   $bookings->save();
   $guests = new Guest;
   $guests->id_number = $request->input('id_number');
   $guests->mobile = $request->input('mobile');
   $guests->save;

}
  return redirect('home');

主视图

 <table class="table table-striped">
                    <thead>
                        <tr>
                          <td>ID</td>
                          <td>Room Name</td>
                          <td>Check-In</td>
                          <td>Check-Out</td>
                          <td>Status</td>
                          <td>Action</td>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($bookings as $booking)
                        <tr>
                            <td>{{$booking['id']}}</td>

                            <td>{{$booking->room->room_name}}</td>

                            <td>{{$booking['checkin_dtime']}}</td>
                            <td>{{$booking['checkout_dtime']}}</td>
                            <td>

预订模式

 public function room()
{
    return $this->belongsTo(Room::class, 'room_id');
}
public function user(){
    return $this->belongsTo(User::class);
}

根据问题,这是您的控制器代码:

$bookings = new Booking;
$bookings->checkin_dtime = $request->input('checkin_dtime');
$bookings->checkout_dtime = $request->input('checkout_dtime');
$bookings->user_id = auth()->user()->id;
$bookings->save();

您没有添加任何 room_id 列。这意味着您的 room_id 在数据库中为空。因此,当您尝试调用关系时,eloquent 无法建立关系,您会收到错误消息。你的代码应该是:

$bookings = new Booking;
$bookings->checkin_dtime = $request->input('checkin_dtime');
$bookings->checkout_dtime = $request->input('checkout_dtime');
$bookings->room_id = $request->input('room_id');
$bookings->user_id = auth()->user()->id;
$bookings->save();