2016-01-23 48 views
0

我有三個相關的表,雖然他們似乎不適合從文檔的任何示例或我不知道哪一個。三方雄辯接力

這裏的表的一個示例:

Devices表:

| id | Name | 
|----|:---------:| 
| 1 | Samsung | 
| 2 | Second | 
| 3 | Some Name | 

Categories表:

| id |  Name  | 
|----|:---------------:| 
| 1 | Some Category | 
| 2 | Camera   | 
| 3 | Other Category | 

Specs表:

| id | Value | category_id | device_id | 
|----|:----------:|-------------|-----------| 
| 1 | Some specs | 2   | 1   | 
| 2 | 13MP | 2   | 1   | 
| 3 | Last specs | 1   | 2   | 

現在讓我們說我想運行一個查詢,如「從相機= 13MP的設備中選擇」。 爲了更加明確,我希望能夠使用where('Camera', '13MP')而不是where('2', '13MP')

我已經有基本的關係設置(Device有很多SpecsCategory有很多SpecsSpecs屬於DeviceCategory)。

我不明白我是如何做出關係的,或者如果雄辯能夠用單個查詢來做到這一點。

回答

3

安裝在你的Devices一流的多對多關係:

public function categories(){ 
    return $this->belongsToMany(App\Category::class)->withPivot('Value'); 
} 

安裝在您的Category類一個多對多的關係:

public function devices(){ 
    return $this->belongsToMany(App\Device::class)->withPivot('Value'); 
} 

然後,如果你想獲得具有1300萬像素的攝像頭,然後設備你可以這樣做:

$devices = Category::where('Name', 'Camera')->first()->devices()->wherePivot('Value', '13MP')->get(); 
+0

它不起作用。我收到以下錯誤:未找到列:1054未知列在'where子句'中的'pivot'(SQL:select * from'categories'其中'Name' = Camera和'pivot' =數值限制1)''。 – Alex

+0

我的回答中有一個錯誤,我調整了它。再試一次。 '$ devices = Category :: where('Name','Camera') - > first() - > devices() - > wherePivot('Value','13MP') - > get();' –