jeudi 7 novembre 2019

How should I use HasManyThrough connecting 3 tables via 2 pivot tables in Laravel?

I am having trouble wrapping my head around the HasManyThrough relationship in Laravel 5.8 which I think is what I need to use, but I am not sure how to implement. I've tried following along a Laracasts video where Jeffrey describes it and read the docs, but I can't seem to grasp the concept and feeling rather stupid right now.

How should I define the relationships in my models and write the correct Eloquent query in my ProductsController to display posts in a product view that shares the same tag id?

For example I have a post tagged with "mbti" and I have a product tagged also with "mbti". How would I go about displaying those related posts in the relevant product view? I've managed to display the tags in the view so far, but I want the posts associated with that tag to display as well. I appreciate any guidance on how I should approach this.

I have 3 tables and 2 pivot tables (some column names removed for brevity):

| products |
+----------+
|id        |
------------

| posts    |
+----------+
|id        |
------------

| tags    |
+----------+
|id        |
------------

| post_tag |
+----------+
|post_id   |
|tag_id    |
------------

| product_tag |
+-------------+
|product_id   |
|tag_id       |
---------------

My models:

Post.php

public function tags() {
   return $this->belongsToMany('App\Tag')->withPivot('tag_id');
}

Tag.php

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

public function products() 
{
  return $this->belongsToMany('App\Product')->withPivot('product_tag');
}

Product.php

public function tags() 
{
  return $this->belongsToMany('App\Tag')->withPivot('product_id');
}


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire