nas
nas

Reputation: 2437

How to write a condition based query?

I have a query to run based on the user type selected. I have around 9 users. Based on 9 users, only first line will be different remaining conditions are going to be same.

Below is the code I am writing. I dont want to repeat the same line again for 9 users.

How can I this query without repeating the condition?

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){
    .....
}

Upvotes: 0

Views: 49

Answers (3)

Dhruv Raval
Dhruv Raval

Reputation: 1583

Use When to make easy Try following code:

    $production = Production::where("yrsno", $currentYear)
        ->orderBy("order")
        ->orderBy("rid")
        ->orderBy("aid")
        ->query();

    $production->when($user_id == 1, function ($query) {
        $query->groupBy('gid', 'rid', 'aid', 'sid');
    });

    $production->when($user_id == 2, function ($query) use ($user) {
        $query->where('gid', $user['sgrp']);
    });

    $results = $production->get()->toArray();

check more example https://stackoverflow.com/a/52333718/8970463

Upvotes: 1

Fariz Keynes
Fariz Keynes

Reputation: 62

$slmids = Production::where("yrsno", $currentYear);

if ($user_id == 1)
    $slmids = $slimds->groupBy('gid', 'rid', 'aid', 'sid');
elseif ($user_id == 2)
    $slmids = $slmids->where('gid', $user['sgrp']);
...
// you can use switch-case if you want

$slmids = $slmids->orderBy('order')
    ->orderBy('rid')
    ->orderBy('aid')
    ->get(['gid', 'rid', 'aid', 'sid'])
    ->toArray();

I believe groupBy must be placed first before orderBy

Upvotes: 1

Brandon
Brandon

Reputation: 9

$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();

You can try like this way.

Upvotes: 1

Related Questions