如何在渴望加载的模型中使用groupBy?

时间:2018-01-10 06:58:11

标签: mysql laravel laravel-5 laravel-eloquent

我希望在groupBy模型上notices同样适用notice_date

$admin = Admin::with([
            'notices' => function($query) use($request)
            {
                $query->where('type', $request->notice_type)
                      ->whereBetween('notice_date', [$request->start_date, $request->end_date])
                      ->oldest('created_time')->groupBy('notices.notice_date');
            }, 'user:id,name'
        ])->get();

因为我想像这样打印

2018-01-10
Admin_name notice1 notice2 notice3
John          abc    abc     pqr
Mary          mno    pqr     abc

2018-01-11
Admin_name notice1 notice2 notice3
abc          mno    pqr     abc
pqr          pqr    pqr     mno

但是当我在查询中使用groupBy时,它会给我一个错误

SQLSTATE[42000]: Syntax error or access violation: 1055 'post.notices.id' isn't in GROUP BY

4 个答案:

答案 0 :(得分:1)

在groupBy函数中指定关系名称

->groupBy('notices.notice_date');

答案 1 :(得分:0)

这是因为您在select statement 中使用的任何列必须在group by子句中出现。首先,您可以尝试在app/database.php

中进行一些更改
    'connections' => [
    'mysql' => [
        'strict' => false,
    ]
]

虽然不推荐,但您可以尝试以下方法 -

$admin = Admin::with([
        'notices' => function($query) use($request)
        {
            $query->select(DB::raw('notice_date'))->where('type', $request->notice_type)
                  ->whereBetween('notice_date', [$request->start_date, $request->end_date])
                  ->oldest('created_time')->groupBy('notice_date');
        }, 'user:id,name'
    ])->get();

您可以阅读this文章,以便更好地了解strict mode

答案 2 :(得分:0)

如果您想按通知日期显示管理员,则应加载如下数据:

$notices = Notice::with('admin.user')
    ->where('type', $request->notice_type)
    ->whereBetween('notice_date', [$request->start_date, $request->end_date])
    ->oldest('created_time')
    ->get();

然后将groupBy()集合方法用作you did before

$grouped = $notices->groupBy('notice_date');

答案 3 :(得分:0)

$user = User::with('items');

$items = collect($user->items);

unset($user->items);

$user->items = $items->groupBy('column');