OrderBy之后如何HasMany和BelongsTo Relationships

I created a relationship between the "Review, Games and Info" tables, unfortunately, though, the main table is Games, and he orders me all for Games, While I would like to order the ID of "review" table.

Models: Review
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id_gioco', 'id');
    }
Models: Giochi
    public function review()
    {
            return $this->belongsTo('App\Models\Review', 'id', 'id_gioco');
    }
    public function infogiochi()
    {
            return $this->belongsTo('App\Models\InfoGiochi', 'id', 'id_gioco');
    }
Models: InfoGiochi
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id', 'id_gioco');
    }
Controller:
$review = Giochi::with('Review','InfoGiochi')->orderBy('id','DESC')->get();

Here is a screenshot of my json:

enter image description here

How do I order content for review table IDs?

You have 2 options. You use a join and order in the sql statement or you order it after retrieving the results in the collection.

Using Join

Giochi::select('giocos.*')
    ->with('Review','InfoGiochi')
    ->leftJoin('reviews', 'reviews.id', '=', 'giocos.id_gioco')
    ->orderBy('reviews.id','DESC')
    ->get();

Sorting Collection

Giochi::with('Review','InfoGiochi')
    ->get()
    ->sortByDesc(function($giochi) {
        return $giochi->review->id;
    });

You can try with a raw query or you can use ->orderBy() directly on review function.

You can modify your relationship query when you fire it:

Giochi::with([ 
     'Review' => function ($query) { return $query->orderBy('id','DESC'); },
     'InfoGiochi' 
])->orderBy('id','DESC');