【发布时间】:2013-08-23 18:54:36
【问题描述】:
我正在构建一个类似 Twitter 的应用程序,其中包含一个提要。在此提要中,我需要显示具有此属性的共享:
-来自我关注的用户的分享
-来自用户的分享,按正面评价排序,但只有前10%
这两个查询我需要以某种方式合并,所以它最终将成为一个数组,其中包含所有适用于此条件的共享,没有任何重复并按 ID 排序,desc
我的表格如下所示:
User, Shares, Follows
Shares:
-user_id
-positive
Follows:
-follower_id
-user_id
-level
我已经尝试过的:
$follower_shares = Share::join('follows', 'shares.user_id', '=', 'follows.user_id')
->where('follows.follower_id', Auth::user()->id)
->where('follows.level', 1)
->get(array('shares.*'));
//count = 10% of total shares
$count = Share::count()/10;
$count = round($count);
$top10_shares = Share::orderBy('positive', 'DESC')
->take($count)
->get();
//sorts by id - descending
$top10_shares = $top10_shares->sortBy(function($top)
{
return -($top->id);
});
//merges shares
$shares = $top10_shares->merge($follower_shares);
现在的问题是,有人告诉我有更好的方法来解决这个问题。 此外,$shares 给了我适用于标准的结果,但是这些共享有重复(行,同时适用于这两个标准)并且总体上不是按 id desc 排序的。
如果你能告诉我如何正确地做到这一点,我会很高兴。
非常感谢!
【问题讨论】:
-
你不能在某处做一个明确的检查,以免重复吗?或者之后在数组上运行 array_unique .....也许我完全误解了你......如果是这样......请忽略我:)
-
array_unique 值得一试 :) 谢谢
-
哦,实际上 $shares 是一个对象...
标签: php mysql sql database laravel