从自引用表中获取Laravel ORM中其他表的列获取N级层次结构JSON

时间:2014-07-29 13:44:35

标签: php laravel-4

我有两张表abcdef。我有这两个表的模型分别命名为AbcDef。在Abc中,我声明了这两个函数:

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');
}

在控制器中,我通过

调用了这些函数
$abc = Abc::with('children')->whereNull('parent')->get();

我已经通过父子关系从表实现了层次结构JSON。我在两个表中都有共同的列名。通过这些方法,我得到了abc表的标题栏。但我想获取def表的标题列。我们怎么做到这一点?

1 个答案:

答案 0 :(得分:0)

使用关系:

// 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

或手动加入关系并选择您需要的任何内容:

public function childrenWithTitle()
{
   return $this->child()->with('children')->orderBy('sort_order')
     ->leftJoin('defs', 'defs.abc_id', '=', 'abcs.id')->select('abc.*', 'def.title');
}

请记住,您需要选择键/外键才能让Eloquent将孩子与父母匹配!

$abc = Abc::with('childrenWithTitle')->whereNull('parent')->leftJoin(...)->first();
$abc->childrenWithTitle->first()->title; // 'title' or null if no row found for this child