<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Post extends Model
{
use HasFactory;
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
}
そして取得部分のソース withの中でorderByするとOK
Post::with(['category' => function ($query){
$query->orderBy('sort');
}])->get();
User::withCount([
'posts AS total_view_count' => function ($query) {
$query->select(DB::raw("SUM(view_count) as view_count_sum"));
}
])->orderBy('total_view_count', 'desc')
->get();
Laravelにてリレーション先のテーブルを対象に
orderBy
をかけたかった