2015-05-24 35 views
0

語境Laravel/SQL:查詢模型,其中的關係= 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

感謝提前:)

回答

0

因此,與複雜的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();