I
I
itpeople2018-03-12 16:38:40
Laravel
itpeople, 2018-03-12 16:38:40

How to get title from another table using table pivot?

Hello.
There are three tables:
post:
id
title
categories:
id
title
category_post - pivot table:
category_id
post_id
Please tell me how to get the title from the categories table that belongs to the post.
From the pivot table, we managed to get the category_id, but this is a number, but the category title is needed.
Thank you all in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2018-03-12
@xpert13

You need to set the correct relays in the models. You should not touch the intermediate table at all, only Laravel needs it, but not you.
Look, for example, I have a blog post with tags, I installed such a relay:

class BlogPost extends Model
{
  ...
  public function tags()
  {
      return $this->belongsToMany('App\BlogTag', 'blog_post_tags');
  }
  ...
}

And now I can do this:
foreach($post->tags as $tag)
{
    echo $tag->name;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question