4

是否可以使用 PDO 从 2 个表中加载数据并将第二个表数据设置为第一个表的子数组?例如:

表:

article (id, title, description) 
links (id, article_id, link)

加载数据 ~ :

 stdClass Object
        (
            [article.id] => 1
            [article.title] => bla bla
            [article.description] => example description
            [article.links] => array (
              [0] => array (
               links.id => 1
               links.article_id => 1
               links.link => .......
              )
              [1] => array (
               links.id => 2
               links.article_id => 1
               links.link => .......
              )            
            )
          )
4

2 回答 2

2

I am not sure how efficient this code would be, but you could use a combination of the group_concat and concat mysql functions to get the data into one row/column from the subquery, then you could bust it back out into an array in PHP.

select
    id,
    title,
    group_concat(concat(b.ID, '@@', b.link)) as linkies
from
    article a
        right outer join links b
            on b.article_id=a.ID
group by
    id,
    title

This will result in something like this coming back in your PDO results:

ID | Title   | linkies
1  | bla bla | 1@@yourLink, 2@@SomeOtherLink
2  | ble ble | 1@@yourLinkRow2, 2@@SomeOtherLinkAgain

Once in PHP, this would be fairily easy to bring back into arrays.

于 2012-09-25T10:40:38.307 回答
1

不,您不能直接从 PDO 获得结果。您需要自己对对象进行水合,这通常称为对象关系映射。

或者您可以尝试一些 ORM 框架,例如Doctrine

于 2012-09-25T10:32:41.940 回答