来自自引用表的 Laravel ORM 获取 N 级层次结构 JSON
问题描述
我正在使用 LARAVEL 4
和 MySQL
后端.
I am using LARAVEL 4
with MySQL
back-end.
我有一个 self-referencing
表,其中包含 id、name、type
和 parent
列.这里,parent
是Id
列的foreign-key
.表中数据如下:
I have a self-referencing
table with columns id, name, type
and parent
.
Here, parent
is foreign-key
of the column Id
. The data in table is as below :
我想要一个使用此关系数据返回 nested JSON
的函数.例如:
I want a function that return nested JSON
using this relational data. For example :
我创建了一个名为 Survey
的 model
,如下所示:
I have created a model
named Survey
as below :
并在 controller
中调用它:
但我没有得到正确的结果,正如我在上面的 JSON
中提到的那样.
But I am not getting the proper result as I have mentioned in JSON
above.
仅提供具有一级层次结构的记录(即组和问题,而不是答案).
gives records with one level hierarchy only (i.e group and questions, not answers).
同时
只提供问题(不提供组和答案).
Gives only questions (Not groups and answers).
我想要整个具有 N 层级的嵌套 JSON 格式的自引用数据.
我也试过了
但发现与上面的 $parent 相同.
But found same as $parent above.
有没有我可以得到想要的结果?
Is there anyway I can get the desired result?
提前谢谢..
推荐答案
以下是手动检索嵌套关系的方法:
Here's how you manually retrieve nested relations:
所以你的情况是:
显然,当关系固定时,这将完成这项工作,但这不是对同一张表建立递归关系的方法.
Obviously this will do the job when the relations are fixed, but it's not the way to go for a recursive relation to the same table.
幸运的是,你可以让这样的关系递归,那么你只需要检索整个树就是这样:
Fortunately, you can make such relation recursive, then all you need to retrieve whole tree is this:
但是,我不会以这种方式为每一行加载父级.
However, I wouldn't load parent for each row this way.
这就是你所需要的:
<小时>
要获得真正的树结构,第一个查询必须仅限于根节点:
To get real tree structure, first query must be limited to only root nodes:
这篇关于来自自引用表的 Laravel ORM 获取 N 级层次结构 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!