doushenken2833 2016-05-30 21:20 采纳率: 0%
浏览 39
已采纳

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

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?

  • 写回答

1条回答 默认 最新

  • dpspn60064 2016-05-30 21:51
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题