我在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();
但是当我在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
关于我在Laravel查询构建器中没有做的任何想法/建议。 我确实想掌握并坚持使用Laravel的查询构建器。 感谢。
答案 0 :(得分:1)
将avg
放在get()
之后,avg
方法适用于集合。所以你想要的是先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');
或者,您也可以使用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();