获取JOIN查询中的平均值,在原始MySql中工作但在Laravel查询构建器中不起作用

时间:2016-12-12 01:00:51

标签: php mysql laravel eloquent

我在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的查询构建器。 感谢。

1 个答案:

答案 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();