如何排序这个雄辩的集合?

如何排序这个雄辩的集合?

问题描述:

I am currently working on a beer application with checkins. A user checkin represents a beer he/she has drank. I am now dealing with checkins of the currently logged in user and also the checkins of their friends which I have set up through a friendship table.

I am grabbing a collection of user friends and an instance of the currently logged in user and I am adding them together like so:

// merge the currently logged in user with their friends
$users = $users->add($user);

I now have a collection of the logged in user and their friends and ultimately want to display some sort of timeline with their checkins. My main issue is that whenever I want to use something like this:

@foreach($users as $user)
     @foreach($user->checkins as $checkin)
         // my code
     @endforeach
 @endforeach

I get all users checkins but I am getting the output chunked/grouped per user. Preferably I would just like to sort them on age and not per user so I can create an actual timeline. Now I am getting a block of all of user 1's checkins followed by a block of user 2's checkins, etc.

How can I prevent this behaviour and simply show the latest checkin down to the oldest one?

我目前正在使用签到的啤酒应用程序。 用户签到代表他/她喝的啤酒。 我现在处理当前登录用户的签到以及我通过友谊表设置的朋友的签到。 p>

我抓住了一组用户朋友和一个 当前登录用户的实例,我将它们加在一起如下: p>

  //将当前登录的用户与他们的朋友合并
 $ users = $ users-&gt  ;添加($ user); 
  code>  pre> 
 
 

我现在有一个登录用户及其朋友的集合,最终想要显示某些时间表和他们的签到。 我的主要问题是每当我想使用这样的东西时: p>

  @foreach($ users as $ user)
 @foreach($ user-> checkins as $  checkin)
 //我的代码
 @endforeach 
 @endforeach 
  code>  pre> 
 
 

我得到所有用户签到但我得到的输出是按用户分块/分组的。 我最好只想按年龄而不是每个用户对它们进行排序,这样我就可以创建一个实际的时间表。 现在我正在获取所有用户1的签到块,然后是一个用户2的签到块等。 p>

如何防止此行为并只显示最新的签到最旧的 一个? p> div>

As you're iterating through users, and only then through their checkins, you're seeing checkins grouped by user. In order to be able to order checkins by age, you need to iterate through checkins directly.

The following should help:

// get IDs of users for which you want to show checkins
$users = $users->add($user);
$userIds = $users->modelKeys();

// load checkins for those users
$checkins = Checkin::whereIn('user_id', $userIds)->orderBy('created_at', 'desc')->with('user')->get();

The $checkins variable will hold list of checkins, ordered by their creation date with latest checkins first. Each of the rows will hold the corresponding user in its user attribute.

You should be able to iterate through all checkins now with:

 @foreach($checkins as $checkin)
   // your code here
   // user is available in $checkin->user
 @endforeach

You might need to adapt the code to match your column/relation names, but it should give you an idea how to solve it.