是否可以附加laravel数据库查询?

时间:2017-11-30 07:50:45

标签: php mysql laravel

控制器中的代码

public function getAthleteProperties(Request $request)
{
    $getAthlete = DB::table('students')
                ->join('sports', 'students.id', '=', 'sports.athlete');
                ->select('students.*', 'sports.*')
                ->get();

    if($request->input('gender') == 1)
    {
        //add this line of queries to $getAthlete queries
        ->where('gender', "m");
    }
    else
        ->where('gender', "f");

    if($request->input('active') == 1)
    {
        //add this line of queries to $getAthlete queries
        ->where('active', "y");
    }
    else
        ->where('active', "n");

    return view('admin', compact('getAthlete'));
}

是否可以在laravel中附加查询?例如,我有上面代码所示的代码,如果性别的条件是1并且active是1,那么在$ getAthlete查询的末尾将变为这样。可能吗?怎么样?

    $getAthlete = DB::table('students')
                ->join('sports', 'students.id', '=', 'sports.athlete');
                ->select('students.*', 'sports.*')
                ->where('gender', "m") //added because condition is true
                ->where('active', "y") //added because condition is true
                ->get();

1 个答案:

答案 0 :(得分:5)

您最初不必使用“get”方法,因为它执行select语句。

public function getAthleteProperties(Request $request)
{
    $getAthlete = DB::table('students')
                ->join('sports', 'students.id', '=', 'sports.athlete');
                ->select('students.*', 'sports.*');

    if($request->input('gender') == 1)
    {
        //add this line of queries to $getAthlete queries
        $getAthlete->where('gender', "m");
    }
    else
        $getAthlete->where('gender', "f");

    if($request->input('active') == 1)
    {
        //add this line of queries to $getAthlete queries
        $getAthlete->where('active', "y");
    }
    else
        $getAthlete->where('active', "n");

    $getAthlete = $getAthlete->get();

    return view('admin', compact('getAthlete'));
}