Support the ongoing development of Laravel.io →
Database Eloquent

Hey,

I have this schema:

table_1: id
table_2: id
table_3: id, table_2_id, table_1_id

I need this schema because one table_1 entry can have many table_3 entries and thus can table_2.

So, over table_1 I can get all table_3 entries. But from there, how can I get the matching table_2 entries? Over the table_2_id it shouldn't be a problem but how can I solve this in laravel?

I tried multiple approaches but I can't get it work. A belongsToThrough would be helpful but it doesn't exist.

Edit: Some additional info:

I tried this approach:

Model from table 1:

public function table3() {
    return $this->hasMany('Table3');
}

Model from table 2:

public function table3() {
    return $this->hasMany('Table3');
}

Model from table 3:

public function table1() {
    return $this->belongsTo('Table1');
}

public function table2() {
    return $this->belongsTo('Table2');
}

And then I call this:

$table1 = Table1::with('table3.table2')->findOrFail($id);

The result shows me the entry from table 1 and the matching data from table 3. But I can't get any data from table 2. It looks like this:

[table3] => Array
    (
        [0] => Array
            (
                [id] => 432
                [table_1_id] => 30
                [table_2_id] => 1
                ...
                [table2] => 
            )

As you can see there are no entries in [table2].

Any advice would be very appreciated. Thanks!

Last updated 3 years ago.
0

You're wrong.
The relationship between table_1 and table_2 is Many-to-Many where table_3 is the pivot table.

0

Lol, you're right. Silly that I didn't see it as I was designing the tables. Thank you for the hint :)

0

Sign in to participate in this thread!

Eventy

Your banner here too?

sleepless sleepless Joined 20 Sep 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.