简体   繁体   English

Laravel-多才多艺

[英]Laravel - Multiple relationships Eloquent

I just started learning laravel, and i'm struglling with Eloquent Relationships! 我刚刚开始学习laravel,并且我正处于雄辩的关系中! I have two tables, they are both multi-level: 我有两个表,它们都是多级的:

Paginas- Paginas-

  • IdPagina PK IdPagina PK
  • name 名称
  • Parent 父级

example: 例:

  idPagina  name   parent 
  1          A      Null
  2          B       1

Categorias - 毛虫-

  • IdCategoria PK IdCategoria PK
  • name 名称
  • Parent 父级
  • IdPagina - FK IdPagina-FK

    Example: 例:

 idCategoria name parent idPagina 1 C Null 2 2 D 1 2 

Well...so I want to get something like this: 好吧...所以我想得到这样的东西:

  • A - Parent 家长

  • B - (A's)Child B-(A的)孩子

  • C - (B's) Child C-(B的)子女

  • D - (C's) Child D-(C的)孩子

Then I have Paginas model: 然后我有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();

       }}

And categorias model: 和categorias模型:

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

 }
}

and now I just want to join both tables! 现在我只想加入两个表!

EDITED 已编辑

Well, i just added the codes Stephen Lewis suggested! 好吧,我刚刚添加了Stephen Lewis建议的代码! But now i can't get the multi-level as i want to, here is the blade code 但是现在我无法获得想要的多级功能,这是刀片服务器代码

@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

well, i just can't get the $categoria related to the $pagina -> children 好吧,我就是无法获得与$ pagina相关的$ categoria->儿童

Add this to the Categoria class: 将此添加到Categoria类中:

public function pagina()
{
    return $this->belongsTo('Pagina', 'idPagina');
}

You can also specify the other side of the relationship, by adding this to the Pagina class: 您还可以通过将关系添加到Pagina类中来指定关系的另一端:

public function categorias()
{
    return $this->hasMany('Categoria', 'idPagina');
}

Further information on how to work with Eloquent relationships is available in the docs . 文档中提供有关如何处理口才关系的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM