如何使用最高平均值的回报运行搜索

时间:2017-06-21 18:08:09

标签: laravel laravel-5

我希望使用Laravel 5.4返回一张桌子并从最高的平均次数下降到每个玩家的最低值

我有两张桌子

**Player**: id, Name, Nationality, accepted
**Batting_innings**: Id, runs, player_id 

模型:

class Player extends Model
{

   public function batIngs()
    {
        return $this->hasMany('App\battingIns','player_id');
    }
}

在我的控制器中,目前我正在使用它:

public function index(Request $request)
{
    //
    $bat = Player::all();

    $batsmen =Player::where('accepted', '=', 1)->orderBy($bat->batIngs->avg('runs');

    $batsmen=$batsmen->paginate(10);
    return view('pages.search')->with('batsmen', $batsmen)

}

我收到未找到batIngs的错误。知道怎么做吗?

1 个答案:

答案 0 :(得分:0)

您不能通过集合或任何外部资源订购,您需要在同一个查询中提供查询或计算字段,在这种情况下您需要使用DB::raw()来计算字段,运行的平均值对于播放器,我会使用查询构建器:

public function index(Request $request)
{

    // Add fields to the select method as you need them
    $result = \DB::table('Player')
        ->join('Batting_innings', 'Player.id', '=', 'Batting_innings.player_id')
        ->select(\DB::raw('Player.id, AVG(Batting_innings.runs) as average_runs'))
        ->where('accepted', '=', 1)
        ->groupBy('Player.id')
        ->orderBy('average_runs','desc')
        ->paginate(10);

    // Turn the collection of arrays into a collection of Player models
    $batsmen = Player::hydrate($result->toArray());  

    return view('pages.search')->with('batsmen', $batsmen)

}

希望这有助于你。