Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel,对关系表中字段的结果进行排序?_Laravel_Eloquent - Fatal编程技术网

Laravel,对关系表中字段的结果进行排序?

Laravel,对关系表中字段的结果进行排序?,laravel,eloquent,Laravel,Eloquent,我有一个玩家列表和另一个游戏统计表 我的名单代码是: $gamers = Gamer::with(['lastGameStat' => function($query) { $query->orderBy('total_points', 'DESC'); }])->paginate(20); 关系: public function lastGameStat() { return $this->hasOne(GameStat::class, 'ga

我有一个玩家列表和另一个游戏统计表

我的名单代码是:

$gamers = Gamer::with(['lastGameStat' => function($query) {
    $query->orderBy('total_points', 'DESC');
}])->paginate(20);
关系:

public function lastGameStat() {
        return $this->hasOne(GameStat::class, 'gamer_id', 'id')->orderBy('created_at', 'DESC');
    }
在关系表中,我有一个字段:
total_points
,通过这个代码,我认为可以按照
total_points
$query->orderBy('total_points','DESC')对玩家列表进行排序


它不起作用,有人能给我一个建议吗?我如何从关系表中对字段结果进行排序?

我想你需要另一个关系或自定义范围来获取玩家的各种游戏统计信息

第二关系 Gamer.php(您的型号)

自定义范围 Gamer.php

class Gamer
{
    public function gameStat()
    {
        return $this->hasOne(GameStat::class);
    }
}
use Illuminate\Database\Eloquent\Builder;

class GameStat
{
    public function scopeBest(Builder $query)
    {
        return $query->orderBy('total_points', 'DESC');
    }
}
GameStat.php

class Gamer
{
    public function gameStat()
    {
        return $this->hasOne(GameStat::class);
    }
}
use Illuminate\Database\Eloquent\Builder;

class GameStat
{
    public function scopeBest(Builder $query)
    {
        return $query->orderBy('total_points', 'DESC');
    }
}
在控制器中:

$gamersWithTheirLatestGameStatistic = Gamer::with(['gameStat' => function($query) {
    $query->latest();
}])->paginate(20);

$gamersWithTheirBestGameStatistic = Gamer::with(['gameStat' => function($query) {
    $query->best();
}])->paginate(20);
请注意,这是未经测试的代码,可能无法工作