To show application_status in result, I’m using DB::raw statement in my query.
DB::raw('
CASE
WHEN status = 0 THEN "Pending"
WHEN status = 1 THEN "Approved"
WHEN status = 2 THEN "Declined"
END AS application_status'
)
How can I convert or write this in accessor?
Is there any other way to write above in laravel way.
$leave_applications = LeaveApplication::select('leave_type','total_days',DB::raw(
'
CASE
WHEN status = 0 THEN "Pending"
WHEN status = 1 THEN "Approved"
WHEN status = 2 THEN "Declined"
END AS application_status'
)
))->where('employee_id', $employee_id)->get();
This is my full query.
I read the laravel documentation and search google for above, but did not found anything.
I found the solution which uses ternary operators. But what if we have more than 2 conditions?
2
Answers
In my opinion, in case you’re not storing the status in the database you should store it in a constant or config variable. We wanna avoid at all cost having different application_status for a given ID and consistency is the key for a project.
With this you will achieve your dessired application_status in the model.
I hope I understood your issue correctly.
you can also create a generated column
https://dev.mysql.com/doc/refman/8.0/en/create-table-generated-columns.html