gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:26:16 26 4
gpt4 key购买 nike

Controller 中的代码

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,事件为 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();

最佳答案

您不必首先使用“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'));
}

更新:

使用最新版本的 laravel a conditional clause方法进行了介绍。所以我们可以这样做:

$getAthlete = DB::table('students')
->join('sports', 'students.id', '=', 'sports.athlete')
->select('students.*', 'sports.*')
->when($request->input('gender') == 1, function ($query) {
return $query->where('gender', 'm');
}, function ($query) {
return $query->where('gender', 'f');
})
->when($request->input('active') == 1, function ($query) {
return $query->where('active', 'y');
}, function ($query) {
return $query->where('active', 'n');
})
->get();

关于php - 是否可以附加 laravel 数据库查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47568374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com