dimanche 15 juillet 2018

Laravel Relations : Get Reviews and associated Users of a Product

I have User, Review and Product Models in my app.
The relations are:

  • User hasMany Reviews
  • Review belongsTo User
  • Product hasMany Reviews
  • Review belongsTo Product

My Table structure is

Products table

id | name | price

Reviews Table

id | review | rating | user_id | product_id 

Users Table

id | name |   email | password

When a specific Product page is visited, I want to display all the reviews of that product along with the users who wrote these reviews. So I tried:

$product = Product::where('id','=',$id)->with('reviews')->with('users')->get();  

Of course that didn't work because Product does not have any direct relation with the Users.
Then I tried Has Many Through relation. In Product Model :

public function users()
{
    return $this->hasManyThrough('App\User', 'App\Review');
}

This requires a product_id column in Reviews table which is there.
It also expects a review_id column in Users table which is not there (and does not make sense to put it in there as a User can have many Reviews).

So what is the proper way of doing this ?

How do I get all the reviews of a specific Product along with the users who wrote those reviews ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire