Rocs Devits
Rocs Devits

Reputation: 1

Laravel, sort result on field from relation table?

I have a list with gamers and another table with game stats.

My list code is:

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

relation:

public function lastGameStat() {
        return $this->hasOne(GameStat::class, 'gamer_id', 'id')->orderBy('created_at', 'DESC');
    }

in relation table I have field: total_points and with this code I thought it's possible to sort list of gamers by total_points $query->orderBy('total_points', 'DESC');

It doesn't work, can somebody give me an advice here how can I sort the result on a field from relation table?

Upvotes: 0

Views: 23

Answers (1)

Dan
Dan

Reputation: 5348

I guess you'll need either another relation or custom scopes to fetch various game stats of a gamer.

Second relation

Gamer.php (your model)

class Gamer
{
    public function bestGameStat()
    {
        return $this
            ->hasOne(GameStat::class)
            ->orderBy('total_points', 'DESC');
    }
}

Custom scopes

Gamer.php

class Gamer
{
    public function gameStat()
    {
        return $this->hasOne(GameStat::class);
    }
}

GameStat.php

use Illuminate\Database\Eloquent\Builder;

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

In your controller:

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

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

Be aware as this is untested code and might not work.

Upvotes: 1

Related Questions