'How to show whole datas from table A and table B according to table C?

Table A

id Name
1 A1
2 A2
3 A3
4 A4
5 A5

Table B

id id_table_A id_table_C Name
1 1 1 Test-1
2 2 1 Test-2
3 1 2 Test-3
4 3 2 Test-4
5 3 1 Test-5
6 5 2 Test-6
7 2 2 Test-7

Table C

id Name
1 C1
2 C2
3 C3

My Question I want to select all datas from table A and also table B, according to id in table C in Laravel (Query Builder or Eloquent doesn't matter). So, it would showing like these:

C1 would showing:

id_table_A Name
A1 Test-1
A2 Test-2
A3 Test-5
A4 NULL
A5 NULL

Or when I choose C2, it would showing like:

id_table_A Name
A1 Test-3
A2 Test-7
A3 Test-4
A4 NULL
A5 Test-6

And C3 will showing like:

id_table_A Name
A1 NULL
A2 NULL
A3 NULL
A4 NULL
A5 NULL

NB: Sorry I don't know how to simplify my question



Solution 1:[1]

You can use a many to many relation

A::class

class A extends Model
{
    public function Cs()
    {
        return $this->belongsToMany(C:class, 'b', 'id_table_a', 'id_table_c')->withPivot('id','name');
    }
}

Then use this relation to get what you need

$as = A::with('Cs')->get();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1