我有3个表格如下所示:
table1
id
name
..
..
table2
id
table1_id
table3_id
name
..
..
table3
id
name
..
..
table1与table2和
具有一对多的关系table2有table3_id,其实际名称在table3
中我想在单个表格中显示所有信息。这是这样的:
table1_id,table1_name,table3_id(这应该简单地替换为table3_name)
我的疑问:
// this gets me 2 tables together
// Query 1
$tables = Table1::with('table2')->get();
// this gets me 1 table3
// Query 2
$table3 = Table3::all();
查询1结果:
[
{ // ROW 1
id : 1, //COL 1
name: 'some name', //COL 2
..
..
table2 : [
{
"id" : 1,
"table1_id" : 1,
"name" : "some name",
"table3_id" : 1 //COL 3
},
{
"id" : 2,
"table1_id" : 1,
"name" : "some name",
"table3_id" : 2 //COL 4
},
{
"id" : 3,
"table1_id" : 1,
"name" : "some name",
"table3_id" : 3 //COL 5
}
]
},
{ // ROW 2
id : 1, // COL 1
name: 'some name', // COL 2
..
..
table2 : [
{
"id" : 1,
"table1_id" : 1,
"name" : "some name",
"table3_id" : 1 //COL 3
},
{
"id" : 2,
"table1_id" : 1,
"name" : "some name",
"table3_id" : 2 //COL 4
},
{
"id" : 3,
"table1_id" : 1,
"name" : "some name",
"table3_id" : 3 //COL 5
}
]
}
]
COL 3,Col 4,Col 5目前已打印了ID,但我希望打印名称。
查询2结果(表3):
[
{
"id" : 1,
"name" : "some name in table 3"
},
{
"id" : 2,
"name" : "some name in table 3"
},
{
"id" : 3,
"name" : "some name in table 3"
}
]
@foreach( $tables as $table)
<tr>
<td>{{ $table->id }}</td>
<td>{{ $table->name }}</td>
@foreach($table->table2 as $table2)
<td>{{ $table2->table3_id}}</td>
@endforeach
<td>{{ $tables->other_fields}}</td>
<td></td>
</tr>
@endforeach
如何修改此代码以按名称替换ID
答案 0 :(得分:1)
您可以使用with
查询嵌套关系。只需使用点表示法提供关系的名称:
$tables = Table1::with(['table2', 'table2.table3'])->get();
只要您建立了正确的外键,就会为与table3
相关的table2
中的每一行提取整个记录。