0

Below shown is my query in SQL Server. It is working fine in SQL server studio. How can I write this in Laravel eloquent format?

I tried both DB::table('Price')... method and Price::where()... Model method. By using both methods I was not able to find the average.

Is this a limitation of the eloquent Query builder? What is the best way to get output for this in Laravel?

select  month([Date]) as Date, 
avg(Oil) as Oil,
avg(Gas) as Gas,
 from [mydatabase].[dbo].[Price] 
 where year([Date]) = 2017
group by (month([Date]))

This is the output I get from sql

3 Answers 3

1

You can acheive this using Raw expressions

  $query = DB::table('Price')
                         ->select(DB::raw('avg(Oil) as Oil, avg(Gas) as Gas, month'))
                         ->where('year', '==', '2017')
                         ->groupBy('month')
                         ->get();
Sign up to request clarification or add additional context in comments.

Comments

0

I got the answer

$result = DB::select(DB::raw("select  month([Date]) as Date, 
avg(Oil) as Oil,
avg(Oil_Parity) as Gas,
 from [mydatabase].[dbo].[Price] 
 where year([Date]) = :year
group by (month([Date]))"),['year'=>$year]);

dd($result);

Comments

0

You can use laravel's built in function DB::raw("complex query goes here").

For your query something like below can be possible

$data = DB::raw("select  month([Date]) as Date, 
avg(Oil) as Oil,
avg(Gas) as Gas,
 from [mydatabase].[dbo].[Price] 
 where year([Date]) = ?
group by (month([Date]))", ['2017']);

For DB::raw() More Check Here

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.