SSPerformance
SSPerformance

Reputation: 21

Problem when getting records from database with relationship table

I'm having trouble relating photos to tags using an intermediate table.

In the example below, how can I select all photos that belong to tag 1 with an Eloquent relationship method in Laravel?

I have these tables:

-Photos Table

 |  id  |    name    | description |
    1     photo1.png      ....
    2     photo2.png      ....
    3     photo3.png      ....
-Tags Table

 |  id  |    name    |
    1      Aesthetic
    2        Dark
-Tags Relations

 | id | tag_id | photo_id |
   1      1         3
   2      1         2
   3      2         1

Upvotes: 2

Views: 47

Answers (1)

Simon
Simon

Reputation: 178

First of, you need to ensure that both Photos and Tags table have the relationship defined.

Under the Photos model you should have the following function:

public function tags() {
    return $this->belongsToMany(
        Tag::class,
        "photos_tags", // the name of the pivot table
        "photo_id",
        "tag_id"
    );
}

Under the Tags model you should have the following function:

public function photos() {
    return $this->belongsToMany(
        Photo::class,
        "tags_photos", // the name of the pivot table
        "tag_id",
        "photo_id"
    );
}

Now to access all the tags that are related to the Photo of id 1, you can call the following:

Photo::findOrFail(1)->tags()->get();

And the same you can do for a specific tag to get all it's photos.

Tag::findOrFail(1)->photos()->get();

Hope this will lead you to what you wish.

Upvotes: 1

Related Questions