0

I got 2 relational tables:

table "categories"
id int(11)
title varchar(255)

table "posts"
id int(11)
title varhcar(255)
category_id int(11) // foreign key

If I select the "categories" table, I would like to get a PHP array with al the categories (as in "SELECT * categories") but including an inner array with all its posts:

Array (
    /* first category */
    [0] = Array (
        [id] => 1
        [title] => "Rock"
        /* all its posts */
        [posts] => Array (
            [0] = Array(
                [id] = 100
                [title] = "Rock post title"
                [category_id] = 1
            )
            [1] = Array(
                [id] = 101
                [title] = "Other rock post title"
                [category_id] = 1
            )
     )
    /* second category */
    [1] = Array (
    )
/* ... */
)

If I just made a "join" query I get all the results combined, something like:

id     title    id    title               category_id
1      Rock     100   "Rock post title"   1
2      Rock     101   "Other rock post"   1
3      Rock     102   "Final rock post"   1

I don't want to make multiple queries, because I think is inefficient.

Is there anyway to achive the desire result with one query?

I know CakePHP manage to return relational tables results in this format, so I'm looking to achieve the same result.

4

2 回答 2

0

连接应该类似于:

select c.id, c.title, p.id, p.title, p.category_id 
from categories c, posts p
where c.id = p.category_id 
order by c.id, p.id
于 2012-07-11T21:50:49.580 回答
0

首先,如果您想要此功能,请考虑使用 ORM 库(例如 CakePHP 和其他框架提供的库),而不是为已经解决的问题滚动您自己的代码。

你不能在 SQL 中做“内部数组”,这不是没有很大的丑陋(比如将记录打包到一个字符串列中,然后在 PHP 中解包它们)。

但是对于一个快速的'n 肮脏的解决方案,只要你在查询中重命名帖子 ID 和标题(例如,'post_id'),就可以使用你原来的连接查询,以避免与类别 ID 混淆。然后遍历结果集并构建您的数组。

$newArray = array();
foreach($resultset as $row) {
    if(!array_key_exists($row['category_id'],$newArray)) {
       $newArray[$row['category_id']] = array('id' => $row['category_id'], 'title' => $row['title'], 'posts' => array());
    }
    $newArray[$row['category_id']]['posts'] = array('id' => $row['post_id'], 'title' => $row['post_title'], 'category_id' => $row['category_id']);
}

我没有在编辑器中编写此代码,因此我为拼写错误道歉。你明白了一般的想法。

于 2012-07-11T23:28:26.277 回答