来自自引用表的 Laravel ORM 获取 N 级层次结构 JSON

Laravel ORM from self referencing table get N level hierarchy JSON(来自自引用表的 Laravel ORM 获取 N 级层次结构 JSON)
本文介绍了来自自引用表的 Laravel ORM 获取 N 级层次结构 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 LARAVEL 4MySQL 后端.

I am using LARAVEL 4 with MySQL back-end.

我有一个 self-referencing 表,其中包含 id、name、typeparent 列.这里,parentId 列的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 :

id  name          type         parent 
1   General       group        NULL
2   What is..?    question     1
3   aa            answer       2
4   bb            answer       2
5   cc            answer       2
6   How is..?     question     1
7   ba            answer       6
8   bb            answer       6
9   Where is..?   question     4
10  ca            answer       9
11  cb            answer       9
12  Who is..?     question     6
13  da            answer       12
14  db            answer       12
15  Specific      group        NULL
16  When is..?    question     15
17  ea            answer       16
18  eb            answer       16
19  Whome is..?   question     2
20  fa            answer       19
21  fb            answer       19
22  fc            answer       19

我想要一个使用此关系数据返回 nested JSON 的函数.例如:

I want a function that return nested JSON using this relational data. For example :

[{
  "id" : 1, 
  "name" : "Geneal", 
  "type" : "group", 
  "children" : [{
      "id" : 2, 
      "name" : "What is..?", 
      "type" : "question", 
      "children" : [{
         "id" : 3, 
         "name" : "aa", 
         "type" : "answer"
      },
      {
         "id" : 4, 
         "name" : "bb", 
         "type" : "answer"
      },
      {
         "id" : 5, 
         "name" : "cc", 
         "type" : "answer"
      }]},
      {
      "id" : 6, 
      "name" : "How is..?", 
      "type" : "question", 
      "children" : [{
         "id" : 7, 
         "name" : "ba", 
         "type" : "answer"
      },
      {
         "id" : 8, 
         "name" : "bb", 
         "type" : "answer"
      }]
   }]
... and so on
}]

我创建了一个名为 Surveymodel,如下所示:

I have created a model named Survey as below :

class Survey extends BaseModel{

    protected $table = 'questions';
    protected $softDelete = false;

    public function parent()
    {
        return $this->belongsTo('Survey', 'parent');
    }

    public function children()
    {
        return $this->hasMany('Survey', 'parent');
    }   
}

并在 controller 中调用它:

$user = Survey::all();
$parent = $user->parent()->first();
$children = $user->children()->get();

但我没有得到正确的结果,正如我在上面的 JSON 中提到的那样.

But I am not getting the proper result as I have mentioned in JSON above.

print_r($parent->toJson()); 

仅提供具有一级层次结构的记录(即组和问题,而不是答案).

gives records with one level hierarchy only (i.e group and questions, not answers).

同时

print_r($children ->toJson());

只提供问题(不提供组和答案).

Gives only questions (Not groups and answers).

我想要整个具有 N 层级的嵌套 JSON 格式的自引用数据.

我也试过了

$user = Survey::with('parent', 'children')->get();

但发现与上面的 $parent 相同.

But found same as $parent above.

有没有我可以得到想要的结果?

Is there anyway I can get the desired result?

提前谢谢..

推荐答案

以下是手动检索嵌套关系的方法:

Here's how you manually retrieve nested relations:

$collection = Model::with('relation1.relation2.relation3')->get();

所以你的情况是:

$surveys = Survey::with('children.children.children')->get();

显然,当关系固定时,这将完成这项工作,但这不是对同一张表建立递归关系的方法.

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:

$surveys = Survey::with('childrenRecursive');

但是,我不会以这种方式为每一行加载父级.

However, I wouldn't load parent for each row this way.

这就是你所需要的:

// Survey model
// loads only direct children - 1 level
public function children()
{
   return $this->hasMany('Survey', 'parent');
}

// recursive, loads all descendants
public function childrenRecursive()
{
   return $this->children()->with('childrenRecursive');
   // which is equivalent to:
   // return $this->hasMany('Survey', 'parent')->with('childrenRecursive);
}

// parent
public function parent()
{
   return $this->belongsTo('Survey','parent');
}

// all ascendants
public function parentRecursive()
{
   return $this->parent()->with('parentRecursive');
}

<小时>

要获得真正的树结构,第一个查询必须仅限于根节点:


To get real tree structure, first query must be limited to only root nodes:

$surveys = Survey::with('childrenRecursive')->whereNull('parent')->get();

这篇关于来自自引用表的 Laravel ORM 获取 N 级层次结构 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)