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

seco's avatar
Level 1

eloquent multiple joins

i have 3 tables Country->Province->Area now i want to use eloquent model to get the data

i want to get the area with its related province with its related country using eloquent

i dont want to use query builder because im using field mutators that i befit from. thanks using laravel 5.2

0 likes
8 replies
Snapey's avatar

Whats wrong with Area::with('province', 'province.country')->get();

seco's avatar
Level 1

can i select some fields with aliases like query builder

ex. select areas.id AS aid and provinces.id AS pid

seco's avatar
Level 1

i want to show them on a datatable and just some fields only and there is some fields are the same name in the 3 tables like id,name

that's why

Snapey's avatar

if you eager load them then the collection will b nested so the name clashes will not matter

seco's avatar
Level 1

i know they are nesting

but im using laravel datatable https://datatables.yajrabox.com/

and in order to show the data on the table i have to write 2 things or every column like this

{data: 'id', name: 'posts.id'},
{data: 'title', name: 'posts.title'},

how i can specify the data and name for fields i want in this case ?

Snapey's avatar

Just reference the nested data through dotted notation?

ie area.province.name or area.province.id

1 like
tylernathanreed's avatar
Level 14

Fun fact: You can Eager Load using closures:

Area::select([
    'id',
    'province_id',
    '<column> AS <alias>',
    /* ... */
])->with([
    'province' => function($query) {
        return $query->select([
            'id',
            'country_id',
            '<column> AS <alias>',
            /* ... */
        ]);
    },
    'province.country' => function($query) {
        return $query->select([
            'id',
            '<column> AS <alias>',
            /* ... */
        ]);
    }
])->get();

Result:

Illuminate\Support\Collection: {
    #items: [
        0 => App\Models\Area {
            'id' => 1,
            'province_id' => 1
            '<alias>' => /* ... */
            'province' => App\Models\Province {
                'id' => 1
                'country_id' => 1,
                '<alias>' => /* ... */
                'country' => App\Models\Country {
                    'id' => 1
                    '<alias>' => /* ... */
                }
            }
        }
        /* ... */
    ]
}

Get be sure to pull in any Foreign Keys / Primary Keys that are used in the joins for the Eager Loading, or else the relationship will return an empty set.

1 like

Please or to participate in this conversation.