mysql - 在 Laravel 中使用 foreach 加入查询
问题描述
我正在尝试学习 Laravel,所以如果我的问题很简单,我深表歉意。
我有 2 个表(table1,table2),如下所示:
table1:
ID date time
1 1 1
2 4 2
3 5 3
表2:
ID V R
1 123 T
1 12 F
1 43 F
2 32 T
2 23 T
3 43 F
因为我有 3 种类型的 ID(可能或多或少)我想使用 table1 将 table2 分成 3 个表。像这样:
table2_1:对于 ID:1
V R
123 T
12 F
43 F
表 2_2:对于 ID:2
V R
23 T
23 T
表 2_3:对于 ID:3
V R
43 F
我想我需要这样的东西:
@foreach ($table1 as $t)
<table class="table">
{!! $t -> ID!!}
<thead>
<tr>
<th scope="col">R</th>
<th scope="col">V</th>
</tr>
</thead>
<tbody>
<!---Query result ---->
</tbody>
@endforeach
在查询结果中,我需要从加入 table1 和 table2 中选择 V 和 R。
但我不知道确切的代码。
任何想法我该怎么做?提前致谢。
解决方案
你甚至可能不需要在table1
这里参与。只需table2
使用一个ORDER BY
子句进行查询,然后迭代结果集,为每个新ID
值生成新的 HTML 表:
$result = DB::table('table2')
->orderBy('ID')
->get();
$prev_id = NULL;
foreach($result as $row) {
$curr_id = $row->ID;
if ($prev_id != NULL && $curr_id != $prev_id) {
echo "</table>";
}
if ($prev_id == NULL || $curr_id != $prev_id) {
$prev_id = $curr_id;
echo "<table class=\"table\" colspan=\"2\">";
echo "<tr><th scope=\"col\">V</th><th scope=\"col\">R</th></tr>";
}
echo "<tr><td>" . $row->V . "</td><td>" . $row->R . "</td></tr>";
}
echo "</table>";