laravel - 如何从表中获取所有行,与数据透视表连接是否有关系?
问题描述
我将 Laravel 用于服务器端并定义了模型的所有关系。
我有如下表结构
table_A
id | title
1 | apple
2 | banana
table_B
id | A_id | C_id
1 | 1 | 1
2 | 1 | 2
3 | 2 | 2
table_C
id | title
1 | green
2 | red
3 | black
输出现在我想要 table_A 中的所有行以及 table_A 行对象中 table_C 中的所有行,如果 A_id 和 C_id 匹配,则将数据保存在 table_C 对象中,否则为空
例子
[
0 : {
id : 1,
title : 'apple',
table_C : [
0 : {
id : 1
title : green
table_B : {
id : 1,
A_id : 1,
B_id : 1
}
},
1 : {
id : 2
title : red
table_B : {
id : 2,
A_id : 1,
B_id : 2
}
},
2 : {
id : 3
title : black
table_B : null
}
]
},
1 : {
id : 1,
title : 'banana',
table_C : [
0 : {
id : 1
title : green
table_B : null
},
1 : {
id : 2
title : red
table_B : {
id : 3,
A_id : 2,
B_id : 2
}
},
2 : {
id : 3
title : black
table_B : null
}
]
}
]
我还定义了 laravel 关系,请指导我更好的方法来跟踪输出。
解决方案
它不会产生确切的结果..
$res = [];
$t1 = DB::table('tableA')->get();
$t3 = DB::table('tableC')->get();
$t2 = DB::table('tableB')->get();
$key = 0;
foreach($t1 as $table1)
{
foreach($t3 as $ke => $table)
{
foreach($t2 as $table2)
{
if($table2->A_id == $table1->id && $table2->C_id == $table->id)
{
$res[$key]['id'] = $table1->id;
$res[$key]['title'] = $table1->title;
$res[$key]['table_c']['id'] = $table->id;
$res[$key]['table_c']['title'] = $table->title;
$res[$key]['table_c']['table_b']['id'] = $table2->id;
$res[$key]['table_c']['table_b']['A_id'] = $table1->id;
$res[$key]['table_c']['table_b']['C_id'] = $table->id;
}
else
{
$res[$key]['id'] = $table1->id;
$res[$key]['title'] = $table1->title;
$res[$key]['table_c']['id'] = $table->id;
$res[$key]['table_c']['title'] = $table->title;
}
}
$key++;
reset($table2);
}
reset($table);
}
dd($res);
输出将是
array:6 [▼
0 => array:3 [▼
"id" => 1
"title" => "apple"
"table_c" => array:3 [▼
"id" => 1
"title" => "green"
"table_b" => array:3 [▼
"id" => 1
"A_id" => 1
"C_id" => 1
]
]
]
1 => array:3 [▼
"id" => 1
"title" => "apple"
"table_c" => array:3 [▼
"id" => 2
"title" => "red"
"table_b" => array:3 [▼
"id" => 2
"A_id" => 1
"C_id" => 2
]
]
]
2 => array:3 [▼
"id" => 1
"title" => "apple"
"table_c" => array:2 [▼
"id" => 3
"title" => "black"
]
]
3 => array:3 [▼
"id" => 2
"title" => "banana"
"table_c" => array:2 [▼
"id" => 1
"title" => "green"
]
]
4 => array:3 [▼
"id" => 2
"title" => "banana"
"table_c" => array:3 [▼
"id" => 2
"title" => "red"
"table_b" => array:3 [▼
"id" => 3
"A_id" => 2
"C_id" => 2
]
]
]
5 => array:3 [▼
"id" => 2
"title" => "banana"
"table_c" => array:2 [▼
"id" => 3
"title" => "black"
]
]
]
推荐阅读
- python - Flappy Bird pygame“鸟”未定义
- point-cloud-library - 如何将 CGAL 点转换为 PCL 点云?
- javascript - 修复定位元素问题
- node.js - 使用 Getstream 获取所有频道
- java - Java问题通过创建学生管理程序
- sas - Proc Export 以在 SAS 中使用格式/布局更新 excel 表
- android - 使用 Android Studio 时通过 USB 连接时无法在手机上运行/调试应用程序(安装时会断开连接)
- sql-server - 如何从具有身份的 SQL Server 获取用户信息
- r - 从 for 循环中的列表访问文件
- metadata - 实时流媒体音频的实时元数据/字幕