简体   繁体   中英

Laravel Eloquent Eager loading confusion

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?

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM