Laravel Eloquent - 计算另一个 table

Laravel Eloquent - get count of another table

我有一个 eloquent 模型 "Athlete" 还有另一个 table 表演。每个运动员有 0 到很多表演。我想获得每位运动员的最佳表现(个人最好成绩),如果运动员还没有任何表现,我想获得 null。

我的运动员模型:

class Athlete extends Model
{

    // I would like to do something like
    public $personalBest = max(performances) - the highest perfomance

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'athletes';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * Get the performances for the Athelete post.
     *
     * @return HasMany
     */
    public function performances()
    {
        return $this->hasMany('App\EloquentModels\Performance', 'athlete_id', "id");
    }
}

我想获得每个运动员的最高表现。希望它确实有意义。

我认为它必须在某个地方得到解答,但我没能找到它。很抱歉,如果我没有找到它。

Performances table
id(int) year(int) performance(float)
-------------------------------------
1       2000      257.3 
2       2001      227.3 

只是总结一下。发布生成的最终原始查询:

select [athletes].[first_name], [athletes].[last_name], MAX(performance) AS personal_best
from [athletes] 
left join [performances] on [athletes].[id] = [performances].[athlete_id] 
group by [athletes].[id], [athletes].[first_name], [athletes].[last_name] 
order by [personal_best] desc

使用 withCount 应该可以完成工作

$athletes= App\Athlete::withCount('performances')->get();

foreach ($athletes as $athlete) {
    echo $athlete->performances_count;
}

如果你想要最好的性能,你可以这样做

 $athletes= App\Athlete::all();

    foreach ($athletes as $athlete) {
        echo $athlete->performances->pluck('performance')->max();
    }

类似于

select e.athelete.id, max(perf.performace) as max_performace
from atheletes ath
  left join performaces perf on ath.id = perf.athelete_id
group by ath.id, max_performace

可能类似于

DB('athletes as ath')::leftJoin('performaces as perf', 'ath.id', 'perf.athelete_id')->select(e.athelete.id, max(perf.performace) as max_performace)->orderBy('max_performace'); 

如果需要,您可以使用 order by max_performace

我想你也可以简单地使用

echo $athlete->performances->max('performance');