Answer the question
In order to leave comments, you need to log in
Eloquent Laravel (many to many) how to get data through intermediate table?
The Product and User models are connected via Feedback.
You need to select all users (User) who left feedback on the product (Product), they are listed in Feedback.
public function users()
{
return $this->belongsToMany('App\Users','App\Feedback', 'user_id', 'id', 'user_id');
}
Answer the question
In order to leave comments, you need to log in
For more convenient work with Eloquent, it is worthwhile to correctly form the architecture.
In your case, it would be more correct to create an intermediate Pivot model with a description of the necessary relationships (users, products).
class Feedback extends Pivot
{
public function users()
{
return $this->belongsTo(User::class);
}
public function products()
{
return $this->belongsTo(Product::class);
}
}
class User extends Authenticatable
{
...
public function products()
{
return $this->belongsToMany(Product::class,
'feedback', 'user_id', 'product_id')
->using(Feedback::class)
->withTimestamps();
}
}
class Product extends Model
{
...
public function users()
{
return $this->belongsToMany(User::class,
'feedback', 'product_id', 'user_id')
->using(Feedback::class)
->withTimestamps();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question