Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel-合并两个查询?_Php_Mysql_Sql_Database_Laravel - Fatal编程技术网

Php Laravel-合并两个查询?

Php Laravel-合并两个查询?,php,mysql,sql,database,laravel,Php,Mysql,Sql,Database,Laravel,我正在构建一个类似Twitter的应用程序,其中包含一个提要。在此提要中,我需要显示具有以下属性的共享: -我正在跟踪的用户的共享 -来自用户的共享,按正面评级排序,但仅前10% 我需要以某种方式合并这两个查询,因此它最终将成为一个数组,其中包含应用于此条件的所有共享,没有任何重复项,并按ID、desc排序 我的桌子是这样的: User, Shares, Follows Shares: -user_id -positive Follows: -follower_id -user_id -le

我正在构建一个类似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排序

如果你能告诉我,如何以正确的方式做到这一点,我将非常高兴


非常感谢

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

// 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();

你能不能在那里的某个地方做一个独特的检查,以避免重复??或者以后在数组上运行数组\u unique…..可能我完全误解了你…..如果是这样的话…请忽略我:)数组\u unique值得一试:)thanksoh实际上$shares是一个对象…哇,这就是我搜索的对象。它比我的更干净,也更完美。感谢拉斐尔:)如何将两个结果与(“图像”)->(“对象”)合并为一个?