2016-01-23 25 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();' –