A
A
Anon33632020-07-29 12:19:45
Laravel
Anon3363, 2020-07-29 12:19:45

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.

5f213e77704ea990111171.png

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

1 answer(s)
A
Anton October, 2020-07-29
@Anon3363

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);
    }
}

then, in the User or Product models, use this pivot-model to create the correct relationship.
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 question

Ask a Question

731 491 924 answers to any question