Eager Loading with filters (where clauses)?

Viewed 47

Is it possible to add where clause to an eager loading method on a model? For example:

class User extends Model {
  public function sources()
    {
        return $this->hasManyThrough(
            Source::class,          // The related model
            UserNetwork::class,  // The intermediate table that connects this model with the related model.
            'user_id',               // The intermediate table's column that connects to this model.
            'network_id',          // The related table's column that connects to the secondLocalKey.
            'id',               // This model's column that connects to the firstKey.
            'network_id'          // The intermediate table's column that connects the related model.
        )
            ->where('xyz_id', $this->xyz_id);
    }
}

Doing this User::with('sources')->get() returns a collection of users with the sources relation but the sources collection is empty. When I run User::first()->sources()->get() it returns just the collection of sources with the actual data.

Isn't eager loading supposed to 'eager load' all the records instead of having to specify the the first() record?

0 Answers
Related