Friday, March 17, 2017

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



via Darama

Advertisement