I am trying to eager load a dynamic scope in Laravel 4.2
I have the following Eloquent class:
class Project extends Eloquent {
protected $table = 'projects';
public function subProjects() {
return $this->hasMany('SubProject');
}
}
On the Subproject
class, I have the following dynamic scope:
public function scopeForUserInPeriod($query, $user, $interval) {
return $query->whereHas('hourRegistrations', function($query) use($user, $interval) {
$query->where('user_id', $user->id)->whereBetween('date', [$interval->from, $interval->to]);
});
}
Now I would like to eagerload the scope when I load my projects, so I do something like.
Project::with('SubProjects.ForUserInPeriod', $user, $period);
Unfortunately, with
only accepts a list of relations to load. I can't seem to find any indications whatsoever on how I am supposed to eagerload scopes that take arguments. :-(
You don't pass anything else but relations when eager/lazy loading.
You use dots to indicate nested relations, not methods on the query.
This is what you want:
Project::with(['subProjects' => function ($q) use ($user, $period) {
$q->forUserInPeriod($user, $period);
}])->get();