【问题标题】:Get column of other table in Laravel ORM from self referencing table get N level hierarchy JSON从自引用表获取 Laravel ORM 中其他表的列获取 N 级层次结构 JSON
【发布时间】:2014-07-30 19:05:47
【问题描述】:

我有两张桌子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 表的标题列。我们如何做到这一点?

【问题讨论】:

  • 你没有告诉我们,这两者有什么关系,所以不可能提出具体的解决方案。猜测是:使用joins
  • 谢谢 deczo....我已经通过 $abc = Abc::with('children') ->leftJoin('def', function($join) { $join->on ('abc.id', '=', 'def.abc_id'); }) ->whereNull('abc.parent') ->orderBy('sort_order', 'ASC') ->get([ 'abc. id', 'def.title' ]);通过这种方法,我从 def 表中获得了仅父行的标题....但是对于子行,我没有从 def 表中获取标题...它来自 abc 表。
  • 每个with 运行它自己的查询,因此对于每个嵌套级别,您每次都需要join 该表。我宁愿使用简单的关系Abc hasMany Def,以便使用来自相关对象的即时加载标题。
  • @deczo 你能粘贴示例代码吗??

标签: php laravel-4


【解决方案1】:

使用关系:

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

【讨论】:

  • 这是否会进行单独的数据库调用以获取每个项目的标题?
  • 通过这种方法,我只有父行...但不是具有 def 表标题的子行。所以请建议我...如果可能的话粘贴您的代码...
  • 不,它不会按每个项目进行查询,而是按嵌套级别进行查询。应该是leftJoin,也许这就是问题所在。使用示例代码在几秒钟内检查编辑
猜你喜欢
  • 2014-08-31
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
  • 1970-01-01
  • 2023-01-11
  • 2012-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多