SELECT
`posts`.`id`,
`posts`.`created_at`,
`posts`.`content`,
`posts`.`replies`,
`groups`.`id` AS `group_id`,
`groups`.`name` AS `group_name`,
`users`.`id` AS `user_id`,
`users`.`name`,
`users`.`surname`,
`users`.`avatar`,
`posts`.`link`,
`posts`.`event_id`,
`events`.`name` AS `event_name`,
`docs`.`id` AS `attachment_id`
FROM `posts`
JOIN `groups`
ON (`groups`.`id` = `posts`.`group_id`)
JOIN `users`
ON (`users`.`id` = `posts`.`user_id`)
LEFT JOIN `events`
ON (`events`.`id` = `posts`.`event_id`)
LEFT JOIN `docs`
ON (`docs`.`post_id` = `posts`.`id`)
WHERE `posts`.`post_id` = 0
AND `posts`.`group_id` = '28'
ORDER BY `posts`.`id` DESC
LIMIT 4
OFFSET 0
This query selects posts for current group. Last thing I need to add is that it selects documents (docs) that are related to that post…
...
`docs`.`id` AS `attachment_id`
...
LEFT JOIN `docs`
ON (`docs`.`post_id` = `posts`.`id`)
...
I will need hashed_name and name from docs table. At the moment, it selects only id, but its not the biggest problem. Problem is that one post may have more that one docs related to it.
In that case, in docs table id (primary keys) aren’t the same, but post_id (so its related to that post) are. For now, if post have more than one attachment, I get ‘n’ entries back… so I have like duplicate posts. That’s the problem.
The goal is to, afterwards, loop trough array like this:
<?php
if(!empty($posts)) {
foreach ($posts as $post) {
echo $post['content'];
foreach ($post['docs'] as $doc) {
echo $doc['name'];
echo $doc['hashed_name'];
}
}
}
?>
How to modify query to get that result? Thanks in advice!
You need to reorganize the array. You are always going to get back a flat result so youll actually have every doc+post+event… you need need to loop through the result an then organize them into a nested structure by whatever you want the primary record to be (in this case the post).