[英]Laravel Eloquent Eager loading confusion
In Laravel I have a model that looks like this: 在Laravel中,我有一个看起来像这样的模型:
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. 这样做时,我收到一条错误消息,说laravel无法找到team.id,因为它仅查询父收件人表。 Wondering what I'm doing wrong, I thought the
with
method was to eager load / inner join records? 想知道我在做什么错,我认为
with
方法是渴望加载/内部联接记录? Do I need to use a DB: inner join instead? 我是否需要使用DB:内部联接? Or am I missing something?
还是我错过了什么?
Use the whereHas
method for this: 为此使用
whereHas
方法:
Recipient::with('location')
->where('company_id', auth()->user()->company_id)
->whereHas('teams', function($q){
return $q->where('id', 10);
})
->get();
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
包含ID,否则将无法使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.