如何在一个急切加载的模型中使用groupby?

w8rqjzmb  于 2021-06-25  发布在  Mysql
关注(0)|答案(4)|浏览(363)

我想申请 groupBynotices 建模依据 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
blpfk2vs

blpfk2vs1#

在groupby函数中指定关系名称

->groupBy('notices.notice_date');
d4so4syb

d4so4syb2#

如果要按通知日期显示管理员,应按以下方式加载数据:

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

然后使用 groupBy() 像以前一样收集方法:

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

nqwrtyyt3#

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

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

unset($user->items);

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

ct3nt3jp4#

那是因为你在 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();

您可以阅读本文以更好地理解 `strict mode` .

相关问题