我正在使用eloquent来查询数据库条目及其对应关系。问题是我需要将$date
变量传递给关系query
,如下所示:
我可以将$date
变量传递给第一个查询,因为它不在with函数中。我怎样才能用第二个实现这个目标?
查询
public static function find_task($type, $date) {
if($type == 'student') {
$mySid = Student::student_id();
$allTasks = TaskAssignment::where('student_id', $mySid)
->with('task')
->where('dueDate', $date)
->orderBy('dueDate', 'asc')
->get();
} elseif($type == 'teacher') {
$myTid = Teacher::teacher_id();
$allTasks = Tasks::where('teacher_id', $myTid)
->with(['assignment' => function ($query) {
$query->where('dueDate', $date);
$query->orderBy('dueDate', 'asc');
}])->get();
} else {
return 'error this page does not exist';
}
return $allTasks;
}
答案 0 :(得分:6)
在闭包中使用use
->with(['assignment' => function ($query) use ($date){
答案 1 :(得分:0)
您可以尝试以下操作:
$user = User::with(array('relationShipMethod' => function($query) use ($request) {
$query->wherePivot('column', $request->column);
}))->first();
relationShipMethod =与您的方法关联另一个表,例如,用户有帖子,relationShipMethod可能是帖子方法