Php 拉雷维尔口若悬河

Php 拉雷维尔口若悬河,php,laravel,laravel-5.3,Php,Laravel,Laravel 5.3,在Laravel中,我有一个模型如下所示: class Recipient extends Model { public $table = 'recipients'; public function location() { return $this->belongsTo('App\Location'); } public function teams() { return $this->belong

在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');
    }

}
要查询该模型,请执行以下操作:

$recipients = Recipient::with('location')
                            ->with('teams')
                            ->where('company_id',Auth::user()->company_id)
                            ->where('teams.id', 10)
                            ->get();
在这样做时,我得到一个错误,即laravel找不到teams.id,因为它只查询父收件人表。不知道我做错了什么,我以为with方法是急于加载/内部连接记录?我需要使用DB:internaljoin吗?还是我遗漏了什么?

请使用where has方法:

Recipient::with('location')
    ->where('company_id', auth()->user()->company_id)
    ->whereHas('teams', function($q){
        return $q->where('id', 10);
    })
    ->get();

尝试显式地添加select语句。有时关系在未选中时不会显示。包括ID,否则它将无法工作