Mysql 如何在即时加载模型中使用groupBy?
我想将Mysql 如何在即时加载模型中使用groupBy?,mysql,laravel,laravel-5,laravel-eloquent,Mysql,Laravel,Laravel 5,Laravel Eloquent,我想将groupBy应用到noticesmodelbynotice\u date上 $admin = Admin::with([ 'notices' => function($query) use($request) { $query->where('type', $request->notice_type) ->whereBetween('noti
groupBy
应用到notices
modelbynotice\u 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
在groupBy函数中指定关系名称
->groupBy('notices.notice_date');
在groupBy函数中指定关系名称
->groupBy('notices.notice_date');
这是因为在
select语句中使用的任何列都必须出现在GROUPBY子句中。首先,您可以尝试在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();
您可以阅读本文以更好地理解严格模式
,因为在选择语句中使用的任何列都必须出现在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();
您可以阅读这篇文章以更好地理解严格模式
如果您想按通知日期显示管理员,您应该像这样加载数据:
$notices = Notice::with('admin.user')
->where('type', $request->notice_type)
->whereBetween('notice_date', [$request->start_date, $request->end_date])
->oldest('created_time')
->get();
然后使用groupBy()
collections方法,如下所示:
如果要按通知日期显示管理员,应按如下方式加载数据:
$notices = Notice::with('admin.user')
->where('type', $request->notice_type)
->whereBetween('notice_date', [$request->start_date, $request->end_date])
->oldest('created_time')
->get();
然后使用groupBy()
collections方法,如下所示:
我认为这应该是公认的答案,因为它非常干净。我认为这应该是公认的答案,因为它非常干净