Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

akc4's avatar
Level 1

MYSQL - how to efficiently "link" two tables together

Hello,

I have 2 tables in my database, one called markers which I store all my google map markers and one called markers_destinations which I store the destinations each marker can have.

markers table:

+----+---------------+------------+------------+---------------------+
| id |  marker_title  | marker_lat | marker_lng | marker_destinations |
+----+---------------+------------+------------+---------------------+
|  1 | test marker 1 | 50.0000000 |  50.000000 |                     |
|  2 | test marker 2 | 51.0000000 |  51.000000 |                     |
|  3 | test marker 3 | 52.0000000 |  51.000000 |                     |
|  4 | test marker 4 | 53.0000000 |  51.000000 |                     |
+----+---------------+------------+------------+---------------------+

markers_destinations table:

+----+-----------+-----------------+
| id | marker_id | destionation_id |
+----+-----------+-----------------+
|  1 |       185 |             1|
|  2 |       185 |             1|
|  3 |       185 |             1|
|  4 |       186 |              2|
|  5 |       186 |              2|
|  6 |       190 |              3|
+----+-----------+-----------------+

Now, I need to somehow link the markers_destinations table with my markers marker_destinations column.

Here is how I am currently doing it :

    $markers = Markers::all();
    $arr = [];

    foreach ($markers as $m) {
    $destinations = MarkersDestinations::where('marker_id', $m->id)->get();

     $dest = [];

        foreach ($destinations as $d) {

            $a = Markers::where('id', $d->destination_id)->get();

            foreach ($a as $b) {
                $dest[] = $b;
            }
        }

        $arr[] = [
            'id' => $m->id,
            'marker_title' => $m->point_name,
            'marer_lat' => $m->marker_lat,
            'marer_lng' => $m->marker_lng,
            'marker_destinations' => $dest,
        ];

    }

return Inertia::render('Home', [
        'markers' => $arr,
    ]);

It works fine, however I feel like there is a much easier/efficient way of doing it. Is this a situation where I need to use the "Join" query?

Thank you for you help

0 likes
4 replies
akc4's avatar
Level 1

@sr57 Thank you, that is exactly what I needed I think.

CorvS's avatar

As @sr57 already mentioned you can work with Eloquent relationships. In your case adding a relationship to your Marker model should do the trick:

public function destinations(): BelongsToMany
{
    return $this->belongsToMany(Marker::class, 'markers_destinations', 'marker_id', 'destination_id');
}
1 like

Please or to participate in this conversation.