我刚刚开始学习laravel,而且我正在与雄辩的关系中喋喋不休! 我有两个表,它们都是多层次的:
Paginas-
示例:
idPagina name parent
1 A Null
2 B 1
分类 -
IdPagina - FK
示例:
idCategoria name parent idPagina 1 C Null 2 2 D 1 2
嗯......所以我想得到这样的东西:
A - 家长
B - (A's)Child
C - (B's)Child
D - (C's)Child
然后我有Paginas模型:
class Paginas extends Eloquent{
public function children() {
return $this->hasMany('app\paginas', 'parent', 'idPagina');
}
public static function tree() {
return static::with(implode('.', array_fill(1, 10, 'children')))->where('parent', '=', null)->get();
}}
分类模型:
class Categoria extends Eloquent{
public function children() {
return $this->hasMany('app\categoria', 'parent', 'idCategoria');
}
public static function tree() {
return static::with(implode('.', array_fill(1, 10, 'children')))->where('parent', '=', null)->get();
}
}
现在我只想加入两张桌子!
EDITED
好吧,我刚刚添加了Stephen Lewis建议的代码! 但是现在我无法获得我想要的多级别,这里是刀片代码
@foreach($paginas as $pagina)
<h1>{{$pagina -> nomePag}}</h1>
@foreach ($pagina -> children as $child)
<h3>{{$child -> nomePag}}</h3>
@foreach($pagina -> categorias as $categoria)
{{$categoria -> nomeCat}}
@endforeach
@endforeach
@endforeach
好吧,我只是无法获得与$ pagina相关的$ categoria - &gt;孩子们
答案 0 :(得分:0)
将其添加到Categoria
类:
public function pagina()
{
return $this->belongsTo('Pagina', 'idPagina');
}
您还可以通过将其添加到Pagina
类来指定关系的另一面:
public function categorias()
{
return $this->hasMany('Categoria', 'idPagina');
}
有关如何使用Eloquent关系的更多信息,请in the docs。