Get column of other table in Laravel ORM from self referencing table get N level hierarchy JSON

好久不见. 提交于 2019-12-25 03:22:38

问题


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();

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?


回答1:


Using relation:

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


来源:https://stackoverflow.com/questions/25016893/get-column-of-other-table-in-laravel-orm-from-self-referencing-table-get-n-level

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!