在Laravel中使用foreach加入查询

时间:2018-10-25 07:16:25

标签: mysql laravel

我正在尝试学习Laravel,所以如果我的问题很简单,我道歉。
我有2个表(table1,table2),如下所示:
table1:

ID       date       time
1          1          1
2          4          2
3          5          3

table2:

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

table2_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

在查询结果中,我需要a从连接table1和table2中选择V和R。
但我不知道确切的代码。
任何想法我该怎么做?预先感谢。

1 个答案:

答案 0 :(得分:0)

您甚至不需要在这里参与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>";