[英]Getting average value in JOIN query, Works in raw MySql but does not work in Laravel query builder
I got this query written out in Laravel query builder, bu when i run it, it returns this error: Call to a member function join() on float 我在Laravel查询构建器中将这个查询写了出来,当我运行它时,它返回此错误: 在float上调用成员函数join()
$avgYield= DairyCropYield::avg('moisture')
->join('dairy_crops','dairy_crops.id','=','dairy_crop_yields.dairy_crop_id')
->join('dairy_crop_varieties','dairy_crops.dairy_crop_variety_id','=','dairy_crop_varieties.id')
->where('dairy_crop_varieties.crop','=',$crop->crop)
->whereYear('harvested_at','=',Carbon::now()->year)
->get();
But when i write the same query in mySql it wroks as exptected: 但是,当我在mySql中编写相同的查询时,它按预期运行:
SELECT AVG(moisture) FROM dairy_crop_yields AS yield JOIN dairy_crops AS crop ON crop.id = yield.dairy_crop_id JOIN dairy_crop_varieties AS variety ON variety.id = crop.dairy_crop_variety_id WHERE variety.crop = 'corn' AND YEAR(harvested_at) = 2015
Any thoughts / suggestions on what I am not doing right in Laravel query builder. 关于我在Laravel查询构建器中做的不正确的任何想法/建议。 I do want to master and stick with Laravel's query builder.
我确实想掌握并坚持使用Laravel的查询生成器。 Thanks.
谢谢。
Put the avg
after the get()
, the avg
method works on a collection. 将
avg
放在get()
, avg
方法适用于集合。 So what you want is to get()
all the result first then only call the avg('moisture')
on the available results. 因此,您想要的是先
get()
所有结果,然后仅在可用结果上调用avg('moisture')
。
$avgYield= DairyCropYield::join('dairy_crops','dairy_crops.id','=','dairy_crop_yields.dairy_crop_id')
->join('dairy_crop_varieties','dairy_crops.dairy_crop_variety_id','=','dairy_crop_varieties.id')
->where('dairy_crop_varieties.crop','=',$crop->crop)
->whereYear('harvested_at','=',Carbon::now()->year)
->get()
->avg('moisture');
Alternately, you can also do something like this using DB::raw
或者,您也可以使用
DB::raw
做类似的事情
$avgYield= DairyCropYield::select(DB::raw('AVG(moisture)'))
->join('dairy_crops','dairy_crops.id','=','dairy_crop_yields.dairy_crop_id')
->join('dairy_crop_varieties','dairy_crops.dairy_crop_variety_id','=','dairy_crop_varieties.id')
->where('dairy_crop_varieties.crop','=',$crop->crop)
->whereYear('harvested_at','=',Carbon::now()->year)
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.