lundi 15 octobre 2018

Eloquent relations belongsToMany()

I'm trying to find all the posts in various categories. I have the 'Post' and 'Category' models related by belongsToMany () as follows:

Post

public function categories()
{
    return $this->belongsToMany('App\Category');
}

Category

public function posts()
{
    return $this->belongsToMany('App\Post');
}

In between there is the pivot table category_post and everything is working well with the relationships.

The problem I have is the following. When the user enters a post I want to show related posts and for that I want to show the posts that belong to the same categories as the post.

If I do the following:

$post = Post::where('slug',$slug)->first();
$relateds = $post->categories->first()->posts()->get();

I recover the posts of the first category, but that post has more associated categories. And I need all the posts.

I have tried with:

$post = Post::where('slug',$slug)->first();
$relateds = $post->categories->get()->posts()->get();

$post = Post::where('slug',$slug)->first();
$relateds = $post->categories->all()->posts()->get();

And several similar things, but none works.

What would be the right way to do this, please? I'm a little desperate already. Thank you.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire