Darama
Darama

Reputation: 3370

What kind of relationship should be?

I have two models: Users and Categories.

I need to get all categories on which user subscribed.

Do, database structure is:

User    Category   UserCategory
___     _________  __________
id      id | name  category_id user_id

Category model is:

 public function user()
    {
        return $this->belongsToMany('App\User', 'user_id', 'id');
    }

User model is:

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

I tried to get all categories on which user subscribed through third table:

$categories =  Category::with("user")->where("id", Auth::user()->id)->get();

It does not work for me

Upvotes: 2

Views: 31

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163798

To get all categories which belong to the user, use the whereHas() method:

$categories = Category::whereHas('users', function($q) use($userId) {
    $q->where('id', $userId);
})->get();

Also, make sure table name is categories_users and define users relationship like this:

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

Upvotes: 2

Related Questions