【发布时间】:2012-07-18 01:26:59
【问题描述】:
我有模型用户、帖子、评论和标签。
- 用户创建帖子。
- 帖子可以有多个评论和标签。
每个模型都有自己的表格,因此有表格“posts”、“cmets”和“tags”。评论有一个外键“post_id”,而标签有一个名为“post_tags”的many_to_many关系表,其中有两个字段:“post_id”和“tag_id”。
我想得到一个嵌套数组,如下所示:
- 我应该运行哪些 MySQL 查询?
- 我想我需要用 PHP 改变结果来获得我的嵌套数组。怎么样?
非常感谢您的帮助:-)
[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
(...
【问题讨论】:
-
第一件事:为什么要一个查询?
-
我们无法在没有数据库架构的情况下为您提供 SQL 查询,因此我们可以查看数据的来源。如果可能的话,这将非常困难,并且将涉及在服务器端对结果数据进行一些解码,这可能(可能会)比仅运行多个查询在计算上更加昂贵。
-
我已更新问题以反映您的反馈。此外,不需要只使用一个 MySQL 查询。我只是认为那是最好的。欢迎任何具有多个查询的解决方案。