我有两个名为'favorites'和'trail'的表。我想为用户展示十大最爱路径。我和他们之间建立了“多对多”的关系。但是,我不知道如何进行查询。什么应该是正确的查询。有人可以帮我找到正确的查询。没有关系,我尝试过这样的事情 -
$favorites = DB::table('favorites')
->join('trails', 'trails.id', '=', 'favorites.trail_id')
->select('favorites.trail_id', 'trails.name')
->get();
第一个是“小径”表,另一个是“收藏夹” -
要获得前10个路径,您需要使用聚合函数来计算每条路径的用户数,并根据计数结果对结果进行排序,然后仅选择10
$favorites = DB::table('trails as t')
->select('t.id', 't.name')
->join('favorites as f', 't.id', '=', 'f.trail_id')
->groupBy('t.id')
->groupBy('t.name')
->orderByRaw('COUNT(DISTINCT f.user_id) DESC')
->limit(10)
->get();