3张桌子之间的怀疑关系

时间:2019-12-18 19:42:42

标签: laravel eloquent

我有这3个表,我想做的是按用户分组的事件。现在,查询将为user_events表的每个寄存器返回一个事件。

用户 (ID,名称,电子邮件,密码)

事件 (id,名称,日期,完成时间)

user_events (用户ID,事件ID)

路线为:

https://api.domain.com/users/{user}/events

这是查询:

function index(Request $request)
{
    if ($request->isJson()) {
        $userId = $request->user('api')->id;
        $events = UserEvents::where('user_id', $userId)
            ->whereHas('events', function($query) {
                $query->where('finish', 0);
            }   )
            ->with(['events' => function($query) {
                $query->where('finish', 0)
                ->orderBy('id', 'desc');
            }])
            ->get();
        Log::info($request->user('api')->id);
        // Fin nuevo

        return response()->json(['events'=>$events], 200);
    }

    return response()->json(['error' => 'Unauthorized'], 401, []);

查询结果:

{
    "events": [
        {
            "user_id": 1,
            "event_id": 1,
            "events": [
                {
                    "id": 1,
                    "name": "Test 1",
                    "date": "09/06/2018",
                    "finish": 0
                }
            ]
        },
        {
            "user_id": 1,
            "event_id": 34,
            "events": [
                {
                    "id": 34,
                    "name": "Test 34",
                    "date": "09/06/2019",
                    "finish": 0
                }
            ]
        }
    ]
}

如何使用户事件按如下方式分组?

{
    "events": [
        {
            "user_id": 1
            "events": [
                {
                    "id": 1,
                    "name": "Test 1",
                    "date": "09/06/2018",
                    "finish": 0
                },
                {
                    "id": 34,
                    "name": "Test 34",
                    "date": "09/06/2019",
                    "finish": 0
                }
            ]
        }
    ]
}

0 个答案:

没有答案