我使用Laravel 4,有两个模型:项目和任务。我的Project.php是
class Project extends 'Eloquent {
protected $guarded = [];
public function tasks()
{
return $this->hasMany('Task');
}
}
我的task。php是
class Task extends 'Eloquent {
protected $guarded = [];
public function project()
{
return $this->belongsTo('Project');
}
}
到现在为止都是很标准的东西。
现在我想显示最近30天。我正在使用nesbot/Carbon,我可以做:
$projects = Project::with('tasks')->where('created_at', '>', Carbon::now()->subDays(30))->get();
这里显示的是最近30天的项目,但我想显示最近30天的任务。在Laravel。我得到这样的建议:
$projects = Project::with(['tasks' => function($query) { $query->where('created_at', '>', Carbon::now()->subDays(30)); }]);
但是这个也不行。
我将感谢任何关于如何从过去30天访问任务的建议,同时使用模型关系,就像我通常在控制器中做的那样。
爱,
乔治:)
您需要使用whereHas
将约束转移到主项目查询。
$constraint = function($query) {
$query->where('created_at', '>', Carbon::now()->subDays(30));
};
Project::with(['tasks' => $constraint])
->whereHas(['tasks' => $constraint])
->get();
注意,如果你想显示所有项目的任务,你可以去掉with()。
这有点低效,可以通过使用连接而不是whereHas来改进,但是应该让您开始。
实际上来自Laravel聊天的答案是正确的:
$projects = Project::with(['tasks' => function($query) { $query->where('created_at', '>', Carbon::now()->subDays(30)); }]);
我刚刚忘记get()-方法。所以正确的方式应该是:
$projects = Project::with(['tasks' => function($query) { $query->where('created_at', '>', Carbon::now()->subDays(30)); }])->get();
关于Connor_VG