MajAfy
MajAfy

Reputation: 3097

Relation between 2 tables with a link table

I have this tables :

topics
-------
id    |   title
------+----------
1     |   Sport
2     |   Social

posts_topics
------------
id    |   post_id    |   topic_id
------+--------------+------------
1     |    1         |     1
2     |    1         |     2

posts
------
id   |   title
-----+----------
1    |   A Test Post

I store topics in topics table and use posts_topics to link between my posts table and topics

now I want select title of topics when selecting posts,

After some searching in StackOverflow and Google, I've written this models:

Posts.php

public function post_topics()
    {
        return $this->hasMany('App\PostTopics');
    }

PostTopics.php

public function topics()
    {
        return $this->hasManyThrough('App\Posts', 'App\Topics', 'id', 'topic_id');

    }

Topics.php

protected $table = 'topics';

and in my controller I trying to fetch:

$post = Posts::with('post_topics')->find($post_id);
dd($post);

Now this code will work but cannot return title of topics.

Upvotes: 2

Views: 1220

Answers (1)

Laerte
Laerte

Reputation: 7083

Change the code to a Many to Many relationship in Posts.php:

public function post_topics()
{
    return $this->belongsToMany('App\Topics', 'posts_topics', 'post_id', 'topic_id');
}

And then call it:

$post = Posts::with('post_topics')->find($post_id);

Try this and check if it works for you.

Upvotes: 1

Related Questions