0

I have a query in MySQL:

SELECT student, ((SUM(mark1)+SUM(mark2))/SUM(mark3)) AS avg FROM your_table

and

SELECT student, (mark1+mark2-mark3) AS result FROM your_table

I like to convert them to Laravel's query builder format query.

But I can't find any way to do that.

1
  • Thanks for answering, but I like to avoid DB:raw. Is there any way? Commented Sep 17, 2015 at 1:28

2 Answers 2

1

You need something like this

Student::select( DB::raw('student, ((SUM(mark1)+SUM(mark2))/SUM(mark3)) AS avg ')->get();
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for answering, but I like to avoid DB:raw. Is there any way?
Querybuilder is trying to help you write SQL... it's a helper. So all of the php you write is eventually going to be converted to SQL anyways. Not all cases will fit into it though so you have to use DB::raw() for advanced use cases. This isn't a bad thing so don't sell yourself on the fact that it is. Raw SQL is 10x faster than php anyways.
Yes, but BD:RAW has a security hole, so everyone should try to avoid that.
Only if your passing it unsanitized data which you shouldn't be doing.
Thanks for let me know
0

Thanks for helping, but I have found the solution-

 $baseQuery =   DB::table('employee')->select('employee_name', DB::raw('employee_salary/employee_extension as employee_salary'), 'employee_position', 'employee_city', 'employee_extension',"employee_joining_date", 'employee_age', 'employee_id');

Should be in this format

Comments

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.