suppose there are two tables
CREATE TABLE IF NOT EXISTS `structure` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT "",
`name` varchar(64) DEFAULT "" COMMENT "",
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT = "";
CREATE TABLE IF NOT EXISTS `structure` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT "",
`realname` varchar(64) DEFAULT "" COMMENT "",
`structure_id` int(11) DEFAULT NULL COMMENT "",
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT = "";
there is an one-to-many relationship between the department table and the personnel table. How to write the interface to generate this structure?
{
data: [{
"id": "", // ID
"name": "", //
"list": [{ //
"id": "", // ID
"realname" : "", //
}],
}]
}
now I have a way to write it, but I don"t think it"s very good (using tp5 syntax), that is, I look up all the data and process it into an array.
function test()
{
$structure = Db::name("structure")->select();
$user = Db::name("user")->select();
foreach ($structure as &value) {
foreach ($user as $k => $v) {
if ($value["id"] == $v["structure_id"]) {
$value["list"][] = $v;
unset($user[$k]);
}
}
}
return $structure;
}