我有3张表, struct 如下:-
产品
id | name |
---|---|
1 | apple |
2 | orange |
twig
id | name |
---|---|
1 | Branch 1 |
2 | Branch 2 |
股票
id | branch_id | product_id | qty |
---|---|---|---|
1 | 1 | 1 | 10 |
2 | 1 | 2 | 20 |
3 | 2 | 1 | 30 |
4 | 2 | 2 | 40 |
预期结果:-
No. | Name | Branch 1 | Branch 2 | Total |
---|---|---|---|---|
1 | apple | 10 | 30 | 40 |
2 | orange | 20 | 40 | 60 |
Below is my code it is working and can get the expected result but I don't like the way I do especially the part $stock[0]->product->name, I think there must be another proper way to do this better not to loop the twig in blade, is it possible to get everything done in query?
库存管理员
$ twig = Branch::get();
$股票 = Stock::get()->groupBy('product_id');
//$股票->toArray() output
array:2 [
1 => array:2 [
0 => array:4 [
"id" => 1
"product_id" => 1
"branch_id" => 1
"qty" => 10
]
1 => array:4 [
"id" => 1
"product_id" => 1
"branch_id" => 2
"qty" => 30
]
]
2 => array:2 [
0 => array:4 [
"id" => 1
"product_id" => 2
"branch_id" => 1
"qty" => 20
]
1 => array:4 [
"id" => 1
"product_id" => 2
"branch_id" => 2
"qty" => 40
]
]
]
股票指数.刀身php
@foreach ($股票 as $stock)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $stock[0]->product->name }}</td>
@foreach ($ twig as $branch)
<td>{{ $stock->firstWhere('branch_id', $branch->id)->qty ?? 0 }}</td>
@endforeach
<td>{{ $stock->sum('qty') }}</td>
</tr>
@endforeach