我有多对多关系表,其中的表codes
是递归的。我关心的是如何显示仅是关系的一部分的递归表。我没有显示任何问题,但问题是它显示了所有孩子。
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
----------------- ----------------- --------------------------
因此在模型Code
public function children()
{
return $this->hasMany(self::class, 'code_parent_id')->with('children');
}
我的查询是
Table::with('codes.children')
->whereId(1)
->first()
我的预期结果是
1 - A
1.1 - B
1.1.1 - C
但是我得到的
1 - A
1.1 - B
1.1.1 - C
1.1.1.1 - D
我知道这里应该有其他查询,我只是不知道如何。我没有在模型中包含所有代码,但我认为这很清楚。
答案 0 :(得分:0)
在Laravel中使用Database Query Builder,可以达到预期的输出。代码如下所示。
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();
但是还有另一种替代方法。这是Eloquent ORM的检查链接,以了解更多信息。