简体   繁体   中英

Laravel Many-to-Many relationship with recursive table

I have Many-to-Many relationship tables and one of the tables codes is recursive. My concern is, how to show the recursive table which is only part of relationship. I have no problem displaying this, but the issue was it shows all children.

    tables                  table_has_codes         codes
-----------------       -----------------       ----------------------
id  | name              table_id| code_id       id  | name | code_parent_id
-----------------       -----------------       ----------------------
1   | table_1               1   |   1           1   |   A  |    null
                            1   |   2           2   |   B  |    1
                            1   |   3           3   |   C  |    2
                                                4   |   D  |    3
-----------------   -----------------       --------------------------

So in model Code

public function children()
    {
        return $this->hasMany(self::class, 'code_parent_id')->with('children');
    }

and my query is

Table::with('codes.children')
       ->whereId(1)
       ->first()

my expected result is

1 - A
1.1 - B
1.1.1 - C

but what I get

1 - A
1.1 - B
1.1.1 - C
1.1.1.1  - D

I know that there should be additional query here I just don't know how. I didn't include all the codes in the models but I think it's clear.

In Laravel using Database Query Builder you can achieve the expected output. Code will look like below.

DB::table('tables')
    ->join('table_has_codes', 'tables.id', 'table_has_codes.table_id')
    ->join('codes', 'table_has_codes.code_id', 'codes.id')
    ->select('codes.id as id', 'codes.name as name', 'codes.code_parent_id as parent_id')
    ->get();

But there is another alternative way as well. That's Eloquent ORM check link for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM