简体   繁体   中英

How do I assign children to parents from a single select statement in PHP using PDO?

I am trying to use a single select statement to get the parents and children from my database. The parents have a parent id of 0, and the children have a parent id corresponding to the assigned id of the parent.

This is how my table currently looks

id      parent_id     title
10      0             TREES
11      0             FLOWERS
12      10            PINE
13      10            WALNUT
14      10            GIANT SEQUOIA
15      11            ROSE
16      11            ORCHIDS
17      10            CACAO

I could do a simple:

SELECT * FROM earth WHERE parent_id = 0

Then loop through the result and get the children

SELECT * FROM earth WHERE parent_id = :id_from_parent

but I was wondering if it was possible (more efficient way) to achieve it with a single select statement and use.

fetchAll(PDO::FETCH_GROUP)

When I use fetch group, I do get the groups, but parents are set in their own category of 0 and then the children are grouped by their parent category.

You could use this query to fetch all the children of each parent at once:

SELECT e1.title AS parent, e2.title AS child
FROM earth e1
JOIN earth e2 ON e2.parent_id = e1.id
ORDER BY e1.id

When used with PDO::FETCH_COLUMN|PDO::FETCH_GROUP this will give you a result like

array('TREES' => array('WALNUT','GIANT SEQUOIA','CACAO','PINE'),
      'FLOWERS' => array('ORCHIDS','ROSE')
     )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM