在每个类别中,用户可以在每个表中添加表格然后记录。但如何在类别页面中显示所有内容?
我在控制器中的功能:
public function show($slug)
{
$tables = FuelAccountingTable::where('user_id', '=', Auth::user()->id)
->where('category_id', '=', $this->getCategory($slug)['id'])
->get();
foreach ($tables as $table) {
$records = FuelAccountingRecord::where('table_id', '=', $table->id)
->get();
}
return view('fuel_accounting.detailed')->with([
'category' => $this->getCategory($slug),
'tables' => $tables,
'records' => $records,
]);
}
和刀片模板(在页面顶部我有@foreach($ tables as $ table):
<form class="form-horizontal" role="form" method="POST"
action="{{ route('fuel_accounting_store', $category->slug) }}">
{{ csrf_field() }}
<input type="hidden" name="table_id" value="{{ $table->id }}">
@component('components.table')
@slot('id')
table-{{ $table->id }}
@endslot
@slot('thead')
<tr>
<th width="20%">Pavadinimas</th>
<th width="20%">ISPILTA L.</th>
<th width="20%">ISPILTA KG.</th>
<th width="20%">VERTE EUR.</th>
<th width="20%"></th>
</tr>
@endslot
@slot('tbody')
@foreach($records as $record)
<tr>
<td>{{ $record->name }}</td>
<td>{{ $record->liters }}</td>
<td></td>
<td></td>
<td></td>
</tr>
@endforeach
<tr>
<td><input type="text" name="name"></td>
<td><input type="number" name="liters"></td>
<td>-</td>
<td>-</td>
<td>
<button type="submit" class="btn btn-success btn-sm"
name="saveRecord">Išsaugoti
</button>
</td>
</tr>
@endslot
@endcomponent
</form>
答案 0 :(得分:0)
我认为FuelAccountingTable
和FuelAccountingRecord
之间的关系是hasMany()
。所以,首先eager load数据:
public function show($slug)
{
$category = $this->getCategory($slug);
$tables = FuelAccountingTable::where('user_id', auth()->id())
->where('category_id', $category['id'])
->with('fuelAccountingRecords')
->get();
return view('fuel_accounting.detailed', compact('category', 'tables', 'records'));
}
然后在视图中更改此内容:
@foreach($records as $record)
要:
@foreach($table->fuelAccountingRecords as $record)
如果正确定义了关系,这将有效:
public function fuelAccountingRecords()
{
return $this->hasMany(FuelAccountingRecord::class);
}