Laravel 5.6:与多个表格和条件的关系

时间:2018-03-16 05:30:10

标签: php laravel laravel-5

考虑一下我是酒店老板,我必须知道与酒店有关的预订.. 我需要所有与我酒店相关的预订.. 是否有任何雄辩的功能加入?怎么样?

如何使用雄辩的关系函数enter image description here

获取拥有者(userid)的酒店预订

3 个答案:

答案 0 :(得分:1)

<强> Hotel.php

class Hotel extends Model

{

    public function userId(){

      return $this->belongsTo(User::class,'user_id');

  }

  public function rooms(){

      return $this->hasMany(Room::class,'hotel_id','id');

  }

}

<强> Room.php

class Room extends Model

{

  public function hotelId(){

    return $this->belongsTo(Hotel::class,'hotel_id');

  }

  public function bookings(){

      return $this->hasMany(Booking::class,'room_id','id');

  }

}

<强> user.php的

class User extends Model

{

  public function hotels(){

        return $this->hasMany(Hotel::class,'user_id','id');

    }

}

下面的代码添加到您的控制器中。

$user = \App\User::find(Auth::id());

$hotels = $user->hotels;



foreach ($hotels as $hotel) {

  $rooms = $hotel->rooms;

  foreach ($rooms as $room) {

    print_r($room->bookings);

  }

}

答案 1 :(得分:0)

在模型中定义与用户的关系

class Booking extends Model{

  /**
 * Get the user that owns the booking.
 */
  public function owner()
  {
    return $this->belongsTo(App\User::class,'user_id,'id');
  }
}

然后在您的控制器中

$bookings = Booking::with('owner')->all(); // or get() or whatever to get 

预订清单

foreach($bookings as $booking){
  echo $booking->user->name; // you have access to owner fields
}

答案 2 :(得分:0)

最后我发现了这个。 预订模式

public function room( )
 {  return $this->belongsTo('App\room');
 }
public function hotel( )
{

    return $this->room()->with(['hotel'=> function($query){
        $query->with('user');
    }]);
}

BookingController

public function owner(Booking $booking )  { 
 return $booking->with('hotel')->get()

接下来是与所有者过滤