Reputation: 890
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
Upvotes: 0
Views: 2071
Reputation: 1979
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']);
Upvotes: 0
Reputation: 3266
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();
Upvotes: 1
Reputation: 890
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);
Upvotes: 0