1
votes

I have tables to store user's menu like below:

Table: modules

  • id
  • name
  • status (will have values: active / inactive)

Table: menus

  • id
  • module_id
  • link

Table: menu_user

  • user_id
  • menu_id
  • join

Table: users

  • id
  • name
  • password

The relationship will be like:

[users]-<menu_user>-[menus]-[modules]

Modules has many Menus; and relationship between Users and Menus is many to many.

I only can get user's menu:

$data = User::with('menus')->where('id', 2);

Any how with Eloquent way that I want to have the users's menu where the modules has active status?

1
Well, I find that seems this one fits my needs: $data = Module::with(['menus' => function ($q) { $q->join('menu_user', 'menus.id', '=', 'menu_user.menu_id') ->where('join', 'include') ->where('user_id', 2); }])->where('status', 'active'); maybe others can improve or had better answers are welcome.. :) - tahara

1 Answers

0
votes

Another approach would be to come from the User end and use a nested relationship to the module, eg.

User::where('users.id', 1)
           ->with(array('menus.module' => function($query) {
                   $query->where('modules.status', '=', 'active');
                })
            )->get();

This is dependent on the following in the Models:

User

public function menus()
{
    return $this->belongsToMany('Menu');
}

Menu

public function module(){
    return $this->belongsTo('Module');
}

Module

public function menu(){
    return $this->hasMany('Menu');
}

Glen