首页 > 解决方案 > 如何编写基于条件的查询?

问题描述

我有一个要根据所选用户类型运行的查询。我有大约 9 个用户。基于 9 个用户,只有第一行不同,其余条件相同。

下面是我正在编写的代码。我不想再为 9 个用户重复同一行。

如何在不重复条件的情况下进行此查询?

if($user_id == 1) {
$slmids = Production::groupBy('gid', 'rid', 'aid', 'sid')
//same
                    ->where("yrsno", $currentYear)
                    ->orderBy("order")
                    ->orderBy("rid")
                    ->orderBy("aid")
                    ->get(['gid', 'rid', 'aid', 'sid'])
                    ->toArray();

}
else if($user_id == 2) {
$slmids = Production::where('gid', $user['sgrp'])
//same
                    ->where("yrsno", $currentYear)
                    ->orderBy("order")
                    ->orderBy("rid")
                    ->orderBy("aid")
                    ->get(['gid', 'rid', 'aid', 'sid'])
                    ->toArray();

}
else if($user_id == 3){
    .....
}

标签: laravellaravel-4

解决方案


$production = Production::where("yrsno", $currentYear)
                    ->orderBy("order")
                    ->orderBy("rid")
                    ->orderBy("aid")
                    ->get(['gid', 'rid', 'aid', 'sid']);

if ($user_id == 1) {
    $production = $production->groupBy('gid', 'rid', 'aid', 'sid');
} else if($user_id == 2) {
    $production = $production->where('gid', $user['sgrp']);
} else if($user_id == 3) {
    ....
}

$result = $production->toArray();

你可以这样试试。


推荐阅读