【问题标题】:Laravel - Merge two Queries?Laravel - 合并两个查询?
【发布时间】: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


【解决方案1】:

我发现这是一个非常干净的解决方案:

// Instead of getting the count, we get the lowest rating we want to gather
$lowestRating = Share::orderBy('positive', 'DESC')
                    ->skip(floor(Share::count() * 0.1))
                    ->take(1)->lists('positive');

// Also get all followed ids
$desiredFollow = Auth::user()->follows()->lists('user_id');

// Select where followed or rating higher than minimal
// This lets the database take care of making them distinct
$shares = Share::whereIn('user_id', $desiredFollow)
               ->orWhere('positive', '>=', $lowestRating[0])
               ->get();

【讨论】:

  • 哇,这就是我搜索的内容。它比我的更干净,而且非常完美。谢谢拉斐尔_ :)
  • 如何将两个with("images")->with("object")的结果合二为一?
猜你喜欢
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 2012-09-02
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多