Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mmaron's avatar

Three tables relation

Hi everybody,

I have a trouble in my head. I know how to make simple relation between two tables, but I want to do in my project some more than only simple "category to resource" relation.

I have 3 tables:

gallery
gallery_category
article

Gallery table is connected to gallery_category table so it is fine. I can display pictures by default, by category and so on.

Then I have Article functionality, that you can basically add title, simple image, content AND additionaly I want to specify which gallery will be linked to each article.

Since I have assigned images in gallery to one category, so I want to choose gallery category that will be related to article. I made this, everything is connected well, but I don't know how to display images from gallery by its category from Article model.

I can do this:

{{ $article->category }}

but, then I want to display images from this category and trying do somethink like this:

{{ $article->category->gallery }}

Here you have my models:

Article.php:

public function category() {
    return $this->belongsTo('App\GalleryCategories');
}

Gallery.php

public function category() {
    return $this->belongsTo('App\GalleryCategories');
}

GalleryCategories:

public function gallery() {
    return $this->belongsTo('App\Gallery');
}
public function article() {
    return $this->belongsTo('App\Article');
}

Is there some 'trick' to do it like I want ? Thanks for attention.

0 likes
2 replies

Please or to participate in this conversation.