1

I have a two models "user" and "user_groups"

there is a relation between the two models like so:

public function usergroup()
{
    return $this->hasOne('App\user_group','id','group_id');
}

I can get all users of the group "drivers" using this method.

 $driversx = User::where('group_id',3)->get();

but I wanna get these users using the "group_name" field in the "user_groups" model.

how can I achieve that?

medo ampir
  • 1,850
  • 7
  • 33
  • 57

3 Answers3

1

Use whereHas() method:

User::whereHas('usergroup', function ($q) {
    $q->where('group_name', 'drivers');
})->get();
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

Generally we used like this way

  public function Menus(){

     return $this->hasOne('App\Models\MainMenu', 'id', 'menu_id');
}

Controller:

$menu_listing=MenuListing::with('Menus')->get();

But if you want to use with group_name go for belongs to

Community
  • 1
  • 1
Nil
  • 513
  • 3
  • 16
0

For your belongsTo relationship :

public function users()
{
    return $this->hasMany('App\User','id','group_id');
}

and then :

$users = UserGroup::where('group_name', 'drivers')->first()->users

the name of your model may be not UserGroup :)

Mathieu Ferre
  • 4,246
  • 1
  • 14
  • 31