Reputation: 4474
In Laravel I have a model that looks like this:
class Recipient extends Model
{
public $table = 'recipients';
public function location()
{
return $this->belongsTo('App\Location');
}
public function teams()
{
return $this->belongsToMany('App\Team');
}
public function company()
{
return $this->belongsTo('App\Company');
}
}
To query that model I do this:
$recipients = Recipient::with('location')
->with('teams')
->where('company_id',Auth::user()->company_id)
->where('teams.id', 10)
->get();
On doing so, I get an error saying that laravel can't find teams.id, as it is only querying the parent recipient table. Wondering what I'm doing wrong, I thought the with
method was to eager load / inner join records? Do I need to use a DB: inner join instead? Or am I missing something?
Upvotes: 0
Views: 53
Reputation: 218
try being explicit and add a select statement. Sometimes a relationship does not show up when not selected. Include the IDs else it won't work
Upvotes: 0
Reputation: 50767
Use the whereHas
method for this:
Recipient::with('location')
->where('company_id', auth()->user()->company_id)
->whereHas('teams', function($q){
return $q->where('id', 10);
})
->get();
Upvotes: 1