2016-11-22 157 views
0

所以我有兩個集合,一個是用戶發佈的帖子,另一個是他正在關注的用戶發佈的帖子。我想將這兩個集合合併在一起,然後將它們排序爲一個集合。 這是我的嘗試:如何合併多個Eloquent集合並按時間戳排序?

$feed = $friendPosts->merge($posts); 
$feed->sortByDesc('created_at'); 

的問題是,他們得到合併到一起,但排序功能似乎不起作用。而不是他們混合在一起,他們來自一部分。所以所有的$friendPosts帖子來了,其他帖子來後病房

我使用苗條框架與枝和雄辯。這裏,這是正在使用的整個控制器,只是一些方面:

public function getSessionProfile($request, $response) 
{ 
//return to sign in if not signed in 
if ($_SESSION['user'] == null) { 
    return $this->view->render($response, 'templates/signin.twig'); 
} 
//grab current user 
$user = User::where('id', $_SESSION['user'])->first(); 
//grab the user's followers 
$followers = Follow::where('follower_id', $user->id)->get(); 
//user posts 
$posts = $user->posts; 

//get the posts made by friendllowers 
foreach ($user->follows as $follow) { 
    $follow = User::where('id', $follow->follower_id)->first(); 
    //posts by people that user is following 
    $friendPosts = $follow->posts; 
} 


//append author to each post made by friendllowers 
$friendPosts->map(function ($post) { 
    $postAuthor = User::where('id', $post->user_id)->first(); 
    $post['authorName'] = $postAuthor->name; 
    $post['authorPicture'] = $postAuthor->avatar; 
    return $post; 
}); 

//append an author to each post made by user 
$posts->map(function ($post) { 
    $postAuthor = User::where('id', $post->user_id)->first(); 
    $post['authorName'] = $postAuthor->name; 
    $post['authorPicture'] = $postAuthor->avatar; 
    return $post; 
}); 

$feed = $friendPosts->merge($posts); 
$feed->sortByDesc('created_at'); 

$this->container->view->getEnvironment()->addGlobal('User', $user); 
//posts by user 
$this->container->view->getEnvironment()->addGlobal('Posts',$user->posts); 
//feed 
$this->container->view->getEnvironment()->addGlobal('Feed',$feed); 
// TODO: make two twig templates one for user only one for feed 
$this->container->view->getEnvironment()->addGlobal('Followings', $user->follows); 
$this->container->view->getEnvironment()->addGlobal('Followers', $followers); 
return $this->view->render($response, 'home.twig'); 

}

回答

0

我解決了這一問題:

需要改變$feed->sortByDesc('created_at');

$feed = $feed->sortByDesc(function($post) 
{ 
return $post->created_at; 
});