Download data from 2 tables and set the data of the second table as a subarray

Is it possible to load data from 2 tables using PDO and set the data of the second table as a subarray from the first table? For instance:

Tables:

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

Uploaded data ~:

  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
source share
2 answers

No, you cannot get the result from PDO directly. You need to moisten objects yourself, which is usually called matching the relationship of objects.

Or you can try some ORM framework like Doctrine .

+1
source

I'm not sure how efficient this code is, but you can use the combination of group_concat and concat of the mysql function to get the data in a single row / column from a subquery, then you can reload it back 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 cause this to return to the PDO results:

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

Once in PHP it would be easy to return to arrays.

+1
source

Source: https://habr.com/ru/post/1436120/


All Articles