doujiao1180 2013-01-26 07:11
浏览 8
已采纳

Laravel Eloquent限制每个用户的结果 - 日期组合

In my database, i got the following table with the following structure:

[taskdate_user]
id : int
user_id : int
taskdate_time : datetime

If i got, for example, 2 rows with the following data:

id : 1
user_id : 1
taskdate_time : 2013-01-25 10:15

id : 2
user_id : 1
taskdate_time : 2013-01-25 11:15

I need to filter out the earliest time for the user and taskdate_time combination. I got the following query right now :

// Get all the TaskdateUser objects for this week
$taskdateuser = TaskdateUser::where('taskdate_time', '>=', $this_monday)->where('taskdate_time', '<', $this_sunday)->order_by('taskdate_time', 'ASC')->get();

This will get me all TaskdateUser objects for the current week, but it does return all of them. Right now, i am ordering by taskdate_time and i'm doing that ascending. So i pick each first object for the user_id - taskdate_time combination.

This seems like a lot of extra code to filter out the first user_id - date combination. Does anybody has a suggestion to simplify this? Many thanks in advance!

EDIT 2 :

I need the earliest time, per user, per date.

I've edited my query in the following way :

    $taskdateuser = TaskdateUser::where('taskdate_time', '>=', $monday)
                                ->where('taskdate_time', '<', $sunday)
                                ->raw_where('id IN 
                                    (
                                        SELECT id
                                        FROM taskdate_user 
                                        GROUP BY date_format(taskdate_time, "%Y-%m-%d"), user_id
                                     )')
                                ->order_by('taskdate_time', 'ASC')
                                ->get();

If i echo all the taskdate_times, the output is as follows :

2013-01-21 14:14:00
2013-01-21 17:47:02
2013-01-25 10:56:00
2013-01-26 17:56:41

I have multiple taskdate_time's on 2013-01-26 and 2013-01-25 which will show up only 1 time. And the 2013-01-21 always shows up 2 times. Why is this?

  • 写回答

1条回答 默认 最新

  • duanqiaoren9975 2013-01-26 07:51
    关注

    Get the latest date from grouped MySQL data

    You will have to use RAW queries, but if I understand what you want, that should help you.

    Something like:

    $taskdateuser = DB::query(SELECT `id`,`user_id`,`taskdate_time` FROM `taskdate_user` WHERE `taskdate_time` IN (SELECT max(`taskdate_time`) FROM `taskdate_user`));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题