L
L
lexstile2021-02-26 18:20:21
MySQL
lexstile, 2021-02-26 18:20:21

What is the correct way to get additional data from neighboring tables on the list page?

There is a view page for a particular item.
There is a page listing these items.

Task: Get multiple related records from another table.
For a specific element, we can write a separate request/method that takes the id of this element and extract the necessary data.

But what to do when the same data is needed on the item list page?
That is, each element has records associated with it from another table. Here we are not tied to a specific id. Here we get just all the elements.

And how to put records from another table inside each element of the array?

Array
(
    [0] => Array
        (
            [id] => 17
            [name] => Киевская Русь
           // чтобы выглядело примерно так
            [elements] => [
                        [field1]  => 'field1'
                        [field1]  => 'field1'
            ]
        )

    [1] => Array
        (
            [id] => 19
            [name] => Скандинавия
        )

    [2] => Array
        (
            [id] => 11
            [name] => СССР
        )

    [3] => Array
        (
            [id] => 15
            [name] => СССР 1
        )

    [4] => Array
        (
            [id] => 18
            [name] => Тест
        )

)


UPD:
1. I can do GROUP_CONCAT and everything will return in a string with some kind of delimiter. Next explode. But this option, it seems to me, is not optimal.
2. You can make a separate request to get data from the second table and then map it in a loop before outputting it. Also, as it seemed, the option is not optimal.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Smirnov, 2021-03-23
@lexstile

You can get everything with one request:

SELECT `country`.`id`, `country`.`name`, `table2`.`field1`, `table2`.`field2`
FROM `country` LEFT JOIN `table2` ON `country`.`id`=`table`.`country_id`
ORDER BY `country`.`id`, `table2`.`field`;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question