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

ahmetbarut's avatar

Establishing 3 table relationships

Hello there

I have a question I have 3 tables, I want it to take the record in the 3rd table according to the records in the 2 tables, but I could not.

My Tables

categories,versions, posts

categories table columns

id, name, description

versions table columns

id, version, category_name

post table columns

title, body, slug, user_id, category_name and version

How can I build the relationship between them

0 likes
5 replies
MichalOravec's avatar

Your table structure should be like this with foreign keys

categories
    id - integer
    name - string
    description - text

versions
    id - integer
    category_id - integer
    name - string

posts
    id
    user_id - integer
    category_id - integer
    version_id - integer
    title - string
    slug - string
    body - text

And you need belongsTo and hasMany relationships

Just follow documentation https://laravel.com/docs/8.x/eloquent-relationships#defining-relationships

For example

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function posts()
    {
        return $this->hasMany('App\Models\Post');
    }
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo('App\Models\Category');
    }
}
1 like
jlrdw's avatar

You should consider watching the free from scratch video series, Jeffrey explains various relationships.

Furthermore much of the code is free on GitHub to download and study.

ahmetbarut's avatar

I read the documents but it doesn't work in the method you said

Please or to participate in this conversation.