Skip to content
Advertisement

Query a model using a relationship

I have a model called unit that has this relationship

/**
 * Get the users associated with the unit
 */
public function users()
{
  return $this->hasMany('AppModelsUserUserData');
}

In the UserData model there is a column called user_id which I am trying to put in my condition in my query. I am trying to do a query like this

Unit::where('user_id', Auth::id())->first()

but there is no user_id column in the Unit table, only though the users relationship

Advertisement

Answer

Ended up doing this

Unit::whereHas('users', function($q) {
    $q->where('user_id', Auth::id());
})->first();
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement