Laravel Eloquent 将变量传递给与关系函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36411826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:31:53  来源:igfitidea点击:

Laravel Eloquent pass variable to with relationship function

phpmysqllaravel

提问by Ricki Moore

I am using eloquent to make a query for a database entry and it's corresponding relationship. The problem is I need to pass the $datevariable into the relationship querylike shown below:

我正在使用eloquent查询数据库条目及其对应关系。问题是我需要将$date变量传递到query如下所示的关系中:

I can pass the $datevariable to the first query because its not inside a with function. How can I achieve this with the second?

我可以将$date变量传递给第一个查询,因为它不在 with 函数内。我怎样才能用第二个来实现这一目标?

Query

询问

    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;
}

回答by Muihlinn

Use usein the closure

use在闭包中使用

->with(['assignment' => function ($query) use ($date){

->with(['assignment' => function ($query) use ($date){

回答by aedork

You can try the following:

您可以尝试以下操作:

$user = User::with(array('relationShipMethod' => function($query) use ($request) {
     $query->wherePivot('column', $request->column); 
}))->first();

relationShipMethod = method with you relationship another table for example users has posts maybe relationShipMethod could be posts method

relationshipShipMethod = 方法与你的关系另一个表例如用户有帖子,可能relationShipMethod 可能是posts 方法