Laravel/SQL:查询模型,其中relationship=X


Laravel/SQL: Query model where relationship = X

上下文

我有以下三种型号:房源、房间和房间类型-

LISTING
|-----|-------------|--------------------|
| ID  |  title      |  description       |
|-----|-------------|--------------------|
| 1   | some title  |  some description  |
| 2   | some title  |  some description  |
| 3   | some title  |  some description  |
etc

ROOMS
|-----|---------------|---------------|--------------------|
| ID  |  room_type_id |  listing_id   | room_description   |
|-----|---------------|---------------|--------------------|
| 1   | 1             |  1            |  some description  |
| 2   | 2             |  1            |  some description  |
| 3   | 1             |  1            |  some description  |
etc
ROOM_TYPES
|-----|------------|
| ID  |  name      |
|-----|------------|
| 1   | Bedroom    |
| 2   | Bathroom   |
| 3   | Kitchen    |
etc

问题

我正在尝试查询具有X个房间类型的房源模型,例如所有拥有>=2间卧室的房源。

我认为这个sql是对的,只是不确定如何在Laravel-中做到这一点

SELECT listing.id, listing.title, count(rooms.id)
FROM listing
JOIN rooms on rooms.listing_id = listing.id
WHERE rooms.`room_type_id` = 10
GROUP BY listing.id
HAVING count(rooms.room_type_id) >= 1

有什么想法吗?

PS。我正在使用Laravel 4

提前感谢:(

因此,在处理了一个复杂的SQL查询之后,我使用了一个模型访问器来实现我的目标:

关于上市模型

public function bedroomCount()
    {
        return $this->rooms()
            ->selectRaw('listing_id, count(*) as count')
            ->where('room_type_id', '=', '1')
            ->groupBy('listing_id');
    }

和查询

$listings = Listing::
            has('bedroomCount', '>=', $x)
            ->get();