Lecturer::query() ->whereHas('libraryItems', function ($query) { $query->where('library_items.news', true); }) ->withCount([ 'libraryItems' => fn($query) => $query->where('library_items.news', true), ]) ->orderByDesc('library_items_count') ->get(), ]); } }