Laravel 5.6-如何获取最后X位来宾的房费?

时间:2019-03-07 20:01:49

标签: php laravel eloquent laravel-5.5 laravel-5.6

对于以下情况,我不知道如何构建有效的口才查询。

用户可以留在房间,公寓,房屋等许多地方,因此我们有一个多态stayable_locations表,但是我们只关注此表的房间stayable_type。当工作人员单击房间时,我们要显示所有可用的房间交易(如果room_deals表中有可用的话),以及每个房间交易的最后3位客人(如果有)。

试图通过雄辩地从下表中获得此输出:

Room 111 (desired output for room deals and guests below)
- Room Deal #1 -> Able, Kane, Eve
- Room Deal #2 -> Eve, Adam

------------------------------------------
$room = Room::where('id',111)->first(); // room 111
// Eloquent query, not sure how to setup model relations correctly
// To get last 3 guest names per room deal [if any] in an efficient query
$room->roomDeals()->withSpecificRoomDealLast3RoomGuestNamesIfAny()->get();

这是表结构:

stayable_locations table [polymorphic]:
id | stayable_id | stayable_type | room_deal_id | room_guest_id
----------------------------------------------------------------
1  |     111     |     room      |       0      | 3 (Steve no room deal)
2  |     111     |     room      |       1      | 1 (Adam room deal) 
3  |     111     |     room      |       1      | 2 (Eve room deal)
4  |     111     |     room      |       1      | 4 (Kane room deal)
5  |     111     |     room      |       1      | 5 (Able room deal)
6  |     111     |     room      |       2      | 1 (Adam room deal)
7  |     111     |     room      |       2      | 2 (Eve room deal)

room_deals table:
id | room_id | room_deal
-----------------------
1  |   111   | Deal A
2  |   111   | Deal B


users table:
id | name
------------
1  | Adam
2  | Eve
3  | Steve
4  | Kane
5  | Able

更新:显示各个模型

用户模型:

class User extends Authenticatable {
    public function stayableLocations() {
      return $this->morphMany('App\StayableLocation', 'stayable');
    }
}

房间交易模式:

class RoomDeal extends Model {
    public function room() {
        return $this->belongsTo('App\Room');
    }

    public function guests() {
        return $this->belongsToMany('App\User', 'stayable_locations', 'room_deal_id', 'room_guest_id');
    }
}

StayableLocation模型:

class StayableLocation extends Model {
    public function stayable() {
        return $this->morphTo();
    }

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

房间模型:

class Room extends Model {
  public function stayableLocations() {
    return $this->morphMany('App\StayableLocation', 'stayable');
  }

  public function roomDeals() {
      return $this->hasMany('App\RoomDeal');
  }
}

有什么想法如何通过有效的口才查询获得所需的输出?

0 个答案:

没有答案