如何合并多个Eloquent集合并按时间戳排序?

时间:2016-11-22 00:36:38

标签: php sorting eloquent twig slim

所以我有两个集合,其中一个由用户发布的帖子,另一个是他正在关注的用户发布的帖子。我想将这两个集合合并在一起,然后将它们排序为一个集合。 这就是我的尝试:

$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');

}

1 个答案:

答案 0 :(得分:0)

我解决了问题:

需要将$feed->sortByDesc('created_at');更改为

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