Я строю трекер времени и пытаюсь заполнить таблицу с общим временем, зарегистрированным для каждого типа категории для каждого месяца года. Я не уверен, что делаю неправильно, но в моей таблице нет данных. Я полагаю, что это связано с тем, как я вызываю свои строки, каждое число представляет category_id, например:
<td>{{ $row[1] ?? '-' }}</td>
Предполагается, что используется общее время из category_id 1, которое составляет сверхурочные часы.
Вот дополнительная информация, чтобы прояснить ситуацию.
Контроллер:
public function show(User $user)
{
$data = collect(array_fill(1, 12, []))
->replace(
$user->times()
->whereYear('start_day', 2019)
->groupBy('category_id', \DB::raw('month(start_day)'))
->select([
'category_id',
\DB::raw('month(start_day) as month'),
\DB::raw('sum(duration) as duration'),
])
->orderBy(\DB::raw('month(start_day)'))
->get()
->mapToGroups(function ($item) {
return [$item['month'] => [
$item['category_id'] => $this->formatDuration($item['duration'])
]];
})
->mapWithKeys(function ($item, $key) {
return [$key => $item->collapse()];
})
)
->mapToGroups(function ($item, $key) {
$month = \DateTime::createFromFormat('!m', $key)->format('M');
return [$month => $item];
});
return view('report.show', compact('data'));
}
Если я dd ($ data), вот пример 1 месяца.
"Oct" => Collection {#330 ▼
#items: array:1 [▼
0 => Collection {#333 ▼
#items: array:1 [▼
0 => "33:20:00"
]
}
]
}
Эта строка должна показывать 1 => "33:20:00", а не 0 => "33:20:00", потому что она принадлежит category_id = 1. Так чтобыть проблема с моими запросами.
Таблица:
<table class="table table-striped table-sm">
<thead>
<tr>
<th scope="col">Month</th>
<th scope="col">Overtime Hours</th>
<th scope="col">Compensation Hours</th>
<th scope="col">Vacation</th>
<th scope="col">Personal Hours</th>
<th scope="col">Sick Hours</th>
</tr>
</thead>
<tbody>
@foreach($data as $month => $row)
<tr>
<th scope="row">{{ $month }}</th>
<td>{{ $row[1] ?? '-' }}</td>
<td>{{ $row[2] ?? '-' }}</td>
<td>{{ $row[3] ?? '-' }}</td>
<td>{{ $row[4] ?? '-' }}</td>
<td>{{ $row[5] ?? '-' }}</td>
</tr>
@endforeach
</tbody>
</table>
Миграция для данных формы:
public function up()
{
Schema::create('times', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->date('start_day');
$table->unsignedBigInteger('category_id');
$table->time('start_time');
$table->time('finish_time');
$table->time('duration');
$table->text('notes');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('category_id')->references('id')->on('categories');
});
}
Миграция для категорий:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->string('type');
});
}
Домашний контроллер:
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
DB::table('categories')->insertOrIgnore([
['type' => 'OT Accrued'],
['type' => 'Comp Time Used'],
['type' => 'Vacation Time Used'],
['type' => 'Personal Hours Used'],
['type' => 'Sick Time']
]);
}