Ad

Three-way Eloquent Relashionships

- 1 answer

I have three tables that are related, though they don't seem to fit any example from the documentation or I'm not realizing which one.

Here's an example of the tables:

Devices table:

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

Categories table:

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

Specs table:

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

Now let's say I want to run a query like "select from devices where camera=13MP". To be more explicit, I want to be able to use where('Camera', '13MP') instead of where('2', '13MP').

I already have the basic relationships setup ( Device has many Specs, Category has many Specs, Specs belongs to Device and Category).

I don't see how I could make the relationships or if Eloquent is able to do this with a single query.

Ad

Answer

Setup a ManyToMany relationship in your Devices class:

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

Setup a ManyToMany relationship in your Category Class:

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

Then if you want to get devices that have cameras of 13MP then you can do this:

$devices = Category::where('Name', 'Camera')->first()->devices()->wherePivot('Value', '13MP')->get();
Ad
source: stackoverflow.com
Ad