我有模型User,Post,Comment和Tag。
每个模型都有自己的表格,因此有表格'帖子','评论'和'标签'。注释有一个名为'post_id'的外键,而Tags有一个名为'post_tags'的many_to_many关系表,其中有两个字段:'post_id'和'tag_id'。
我想获得一个嵌套数组,如下所示:
非常感谢你的帮助: - )
[0] => Array
(
[Post] => Array
(
[id] => 1
[title] => First article
[content] => aaa
[created] => 2008-05-18 00:00:00
)
[Comment] => Array
(
[0] => Array
(
[id] => 1
[post_id] => 1
[author] => Daniel
[email] => dan@example.com
[website] => http://example.com
[comment] => First comment
[created] => 2008-05-18 00:00:00
)
[1] => Array
(
[id] => 2
[post_id] => 1
[author] => Sam
[email] => sam@example.net
[website] => http://example.net
[comment] => Second comment
[created] => 2008-05-18 00:00:00
)
)
[Tag] => Array
(
[0] => Array
(
[id] => 1
[name] => Awesome
)
[1] => Array
(
[id] => 2
[name] => Baking
)
)
)
[1] => Array
(
[Post] => Array
(...
答案 0 :(得分:3)
你最好做3次查询。
首先获取帖子(如果需要,可以左键加入用户),并将其存储为:
$list[$row['post_id']]['Post'] = $row;
然后获取所有评论后的评论并将其存储为
$list[$row['post_id']]['Comment'][$row['comment_id']] = $row;
然后获取所有后标记
$list[$row['post_id']]['Tags'][$row['tag_id']] = $row;
比尝试使用单个查询更有效, 作为单个查询将最终多次发送相同的数据