Laravel 三方雄辩的关系
我有三个相关的表,尽管它们似乎不适合文档中的任何示例,或者我不知道是哪一个 下面是一个表格示例:Laravel 三方雄辩的关系,laravel,laravel-5,eloquent,laravel-5.1,Laravel,Laravel 5,Eloquent,Laravel 5.1,我有三个相关的表,尽管它们似乎不适合文档中的任何示例,或者我不知道是哪一个 下面是一个表格示例: 设备表: | id | Name | |----|:---------:| | 1 | Samsung | | 2 | Second | | 3 | Some Name | | id | Name | |----|:---------------:| | 1 | Some Category | | 2 | Camera |
设备
表:
| id | Name |
|----|:---------:|
| 1 | Samsung |
| 2 | Second |
| 3 | Some Name |
| id | Name |
|----|:---------------:|
| 1 | Some Category |
| 2 | Camera |
| 3 | Other Category |
| id | Value | category_id | device_id |
|----|:----------:|-------------|-----------|
| 1 | Some specs | 2 | 1 |
| 2 | 13MP | 2 | 1 |
| 3 | Last specs | 1 | 2 |
类别
表格:
| id | Name |
|----|:---------:|
| 1 | Samsung |
| 2 | Second |
| 3 | Some Name |
| id | Name |
|----|:---------------:|
| 1 | Some Category |
| 2 | Camera |
| 3 | Other Category |
| id | Value | category_id | device_id |
|----|:----------:|-------------|-----------|
| 1 | Some specs | 2 | 1 |
| 2 | 13MP | 2 | 1 |
| 3 | Last specs | 1 | 2 |
规格
表格:
| id | Name |
|----|:---------:|
| 1 | Samsung |
| 2 | Second |
| 3 | Some Name |
| id | Name |
|----|:---------------:|
| 1 | Some Category |
| 2 | Camera |
| 3 | Other Category |
| 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')
我已经有了基本关系设置(设备
有许多规格
,类别
有许多规格
,规格
属于设备
和类别
)
我不知道如何建立关系,或者Eloquent是否能够通过一个查询实现这一点。在您的
设备
类中设置多个关系:
public function categories(){
return $this->belongsToMany(App\Category::class)->withPivot('Value');
}
在您的
类别中设置多个关系
类:
public function devices(){
return $this->belongsToMany(App\Device::class)->withPivot('Value');
}
然后,如果您想获得具有13MP摄像头的设备,则可以执行以下操作:
$devices = Category::where('Name', 'Camera')->first()->devices()->wherePivot('Value', '13MP')->get();
在
设备
类中设置多个关系:
public function categories(){
return $this->belongsToMany(App\Category::class)->withPivot('Value');
}
在您的
类别中设置多个关系
类:
public function devices(){
return $this->belongsToMany(App\Device::class)->withPivot('Value');
}
然后,如果您想获得具有13MP摄像头的设备,则可以执行以下操作:
$devices = Category::where('Name', 'Camera')->first()->devices()->wherePivot('Value', '13MP')->get();
它不起作用。我收到以下错误:
未找到列:1054“where子句”(SQL:select*from
categories`whereName
=Camera andpivot
=value limit 1)中的未知列“pivot”。`。再试一次<代码>$devices=Category::where('Name','Camera')->first()->devices()->wherePivot('Value','13MP')->get()代码>它不工作。我收到以下错误:未找到列:1054“where子句”(SQL:select*from
categories`whereName
=Camera andpivot
=value limit 1)中的未知列“pivot”。`。再试一次<代码>$devices=Category::where('Name','Camera')->first()->devices()->wherePivot('Value','13MP')->get()代码>