我想知道是否可以通过1个查询按日期对约会进行分组,因此我的响应将是这样的(在JSON中):
{
"appointmentsByDay":[
"01-07-2018":[
{
"appointment":"test"
},
{
"appointment":"test"
}
],
"02-07-2018":[
{
"appointment":"test"
},
{
"appointment":"test"
}
],
..................
"31-07-2018":[
{
"appointment":"test"
},
{
"appointment":"test"
}
]
]
}
我知道这可能会在一个月中的所有日期中循环,但随后我必须在一个月内最多调用31次类似的查询。
当前,我在下面的方式中得到一个月内的所有约会,但这些约会不是每天分组,落在较大范围内的约会将被排序错误:
$startOfMonth = Carbon::parse($date)->startOfMonth();
$endOfMonth = Carbon::parse($date)->endOfMonth();
$appointments = Appointment::
where('user_id', '=', $userId)->
where(function ($query) use($endOfMonth, $startOfMonth) {
$query->where(function ($query) use($endOfMonth, $startOfMonth) {
$query->where('from_date', '<', $startOfMonth->format('Ymd'))
->where('to_date', '>', $endOfMonth->format('Ymd'));
})
->orWhere(function ($query) use($endOfMonth, $startOfMonth) {
$query->where('from_date', '>=', $startOfMonth->format('Ymd'))
->where('to_date', '<=', $endOfMonth->format('Ymd'));
})
->orWhere(function ($query) use($endOfMonth, $startOfMonth) {
$query->where('from_date', '<', $startOfMonth->format('Ymd'))
->where('to_date', '>=', $startOfMonth->format('Ymd'));
})
->orWhere(function ($query) use($endOfMonth, $startOfMonth) {
$query->where('from_date', '<=', $endOfMonth->format('Ymd'))
->where('to_date', '>', $endOfMonth->format('Ymd'));
});
})
->with(user')
->get();
我的模型如下:
namespace App\Models;
use Reliese\Database\Eloquent\Model as Eloquent;
class Appointment extends Eloquent
{
protected $table = 'appointments';
public $timestamps = false;
protected $fillable = [
'from_date',
'to_date',
'title'
];
}
我的约会表如下:(我正在使用MYSQL)
+-----------+----------------+---------------------+-------------------+
| id (int) | title (varchar)| from_date (varchar) | to_date (varchar) |
+-----------+----------------+---------------------+-------------------+
| 1 | appointment1 | 20180725 | 20180725 |
+-----------+----------------+---------------------+-------------------+
| 2 | appointment2 | 20180726 | 20180726 |
+-----------+----------------+---------------------+-------------------+
| 3 | appointment3 | 20180723 | 20180812 |
+-----------+----------------+---------------------+-------------------+
| 4 | appointment4 | 20180726 | 20180726 |
+-----------+----------------+---------------------+-------------------+
| 5 | appointment5 | 20180612 | 20181123 |
+-----------+----------------+---------------------+-------------------+