从自引用表获取Laravel ORM中其他表的列,获取N级层次结构JSON [英] Get column of other table in Laravel ORM from self referencing table get N level hierarchy JSON
问题描述
我有两个表abc
和def
.我有这两个表的模型,分别命名为Abc
和Def
.在Abc
中,我声明了以下两个函数:
I have two tables abc
and def
. I have models of these two tables named respectively Abc
and Def
. In Abc
, I declare these two functions:
public function child()
{
return $this->hasMany('Abc', 'parent');
}
// recursive, loads all descendants
public function children()
{
return $this->child()->with('children')->orderBy('sort_order');
}
// parent
public function parent()
{
return $this->belongsTo('Abc','parent');
}
// all ascendants
public function parentRecursive()
{
return $this->parent()->with('parentRecursive');
}
在控制器中,我通过以下方式调用了这些功能
In controllers I called these functions by
$abc = Abc::with('children')->whereNull('parent')->get();
我已经通过父子关系从表实现了层次结构JSON.我在两个表中都有通用的列名.通过这些方法,我获得了abc
表的标题列.但是我想获取def
表的标题列.我们该怎么做?
I have implemented level hierarchy JSON from table through parent child relation. I have common column name in both tables. Through these method I get the title column of abc
table. But I want to fetch title column of def
table. How we can do this?
推荐答案
使用关系:
// Abc model
public function defs()
{
return $this->hasMany('Def', 'abc_id');
}
public function childrenWithDef()
{
return $this->child()->with('childrenWithDef.defs')->orderBy('sort_order');
}
// then:
$abc = Abc::with('childrenWithDef', 'defs')->whereNull('parent')->get();
// every Abc has related Def collection
foreach ($abc->first()->defs as $def) $def->title
或手动加入该关系并选择所需的任何内容:
or manually joining on the relation and selecting whatever you need:
public function childrenWithTitle()
{
return $this->child()->with('children')->orderBy('sort_order')
->leftJoin('defs', 'defs.abc_id', '=', 'abcs.id')->select('abc.*', 'def.title');
}
请记住,您需要选择键/外键,以便雄辩地将孩子与父母配对!
Remember that you need keys/foreign keys to be selected in order to let Eloquent match children to their parents!
$abc = Abc::with('childrenWithTitle')->whereNull('parent')->leftJoin(...)->first();
$abc->childrenWithTitle->first()->title; // 'title' or null if no row found for this child
这篇关于从自引用表获取Laravel ORM中其他表的列,获取N级层次结构JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!