如何在Laravel Elequent Query Builder中编写复杂的sql查询

时间:2017-01-09 12:35:18

标签: sql laravel laravel-5.3

下面显示的是我在SQL Server中的查询。它在SQL server studio中运行良好。我怎么用Laravel雄辩的格式写这个?

我尝试了DB :: table(' Price')...方法和Price :: where()...模型方法。通过使用这两种方法,我无法找到平均值。

这是一个雄辩的“查询”构建器的限制吗? 在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 个答案:

答案 0 :(得分:1)

您可以使用Raw expressions

实现此目的
  $query = DB::table('Price')
                         ->select(DB::raw('avg(Oil) as Oil, avg(Gas) as Gas, month'))
                         ->where('year', '==', '2017')
                         ->groupBy('month')
                         ->get();

答案 1 :(得分:0)

我得到了答案

$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);

答案 2 :(得分:0)

  

您可以使用laravel内置函数 DB :: raw("复杂查询到此处")

对于您的查询,可以使用以下内容

$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