Laravel一对多关系不起作用

问题描述 投票:0回答:1

我正在完成酒店预订系统的任务。我有一张叫预订的桌子,还有另一间桌子。我在它们之间做了一对多的关系,我想将房间名称返回到主视图,但它始终显示“试图获取非对象的属性”。这是我的代码。预订Controllerclass GuestBookingController扩展Controller

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);
}
php laravel forge
1个回答
0
投票

更改您的关系模型

public function room()
{
    return $this->belongsTo(Room::class, 'room_id');
}
public function user()
{
    return $this->belongsTomany(User::class, 'room_id');
}
© www.soinside.com 2019 - 2024. All rights reserved.