【问题标题】:How to merge multiple Eloquent collections and sort them by timestamp?如何合并多个 Eloquent 集合并按时间戳排序?
【发布时间】:2016-11-22 00:36:38
【问题描述】:

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

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

问题是它们确实合并在一起,但排序功能似乎不起作用。它们不是混合在一起,而是分成几部分。所以所有$friendPosts 的帖子都来了,其他的帖子都在病房之后来了

我正在使用纤细的框架以及 twig 和 eloquent。这是使用它的整个控制器,仅用于某些上下文:

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

}

【问题讨论】:

    标签: php sorting eloquent twig slim


    【解决方案1】:

    我解决了这个问题:

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

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

    【讨论】:

      猜你喜欢
      • 2015-09-17
      • 2014-05-29
      • 2018-11-10
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 2014-01-16
      相关资源
      最近更新 更多