0

Hello fellow developers, I'm trying to convert my query into eloquent code,but as I was using "CASE" commands among other commands I decided to insert the select section into a DB::raw but now I experience some syntax error or access violation:1055, here is my sql:

SELECT pa.id_budget_total,pa.name,CASE WHEN co.budget IS null THEN pa.amount ELSE pa.amount - SUM(co.budget) END AS left 
    FROM budget_total pa LEFT JOIN convening co ON pa.id_budget_total = co.budget_total 
    where pa.status = 1 GROUP BY pa.name

I kind of converted it to eloquent but when I add co.budget it tells me the error code followed by that co.budget is not group by, and yes it displays no error if I add it within the groupBy but that'd change the whole result. Here it's the eloquent code:

budget_total::select(DB::raw("pa.id_budget_total,pa.name, CASE WHEN co.budget IS null THEN pa.amount ELSE pa.amount - SUM(co.budget) END AS restante"))
->from("budget_total as pa")->leftJoin("convocatoria as co","pa.id_budget_total","=","co.id_budget_total")->where("pa.status", 1)
->groupBy("pa.id_budget_total","pa.name","pa.amount")->get();
3
  • Please explain the logic behind your CASE expression. Commented Oct 1, 2018 at 23:44
  • I'm getting all the related convening-budgets and substracting them from the total budgets but in case that there's no convening budgets related to a total budget I just print the total budget(in order to don't get a NULL value) Commented Oct 2, 2018 at 0:20
  • yeah, I'm trying already that, thank you Commented Oct 2, 2018 at 0:25

1 Answer 1

1

One option would be to always use the ELSE condition, but then COALESCE a NULL sum to zero.

budget_total::select(DB::raw("pa.id_budget_total, pa.name,
    pa.amount - COALESCE(SUM(co.budget), 0) AS restante"))
    ->from("budget_total as pa")
    ->leftJoin("convocatoria as co", "pa.id_budget_total", "=", "co.id_budget_total")
    ->where("pa.status", 1)
    ->groupBy("pa.id_budget_total", "pa.name", "pa.amount")
    ->get();
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much @Tim it works perfectly! I really appreciate it!
well I just had to delete the "END" word before AS restante to get it working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.