如何在laravel 5.4中建立三个表关系

时间:2017-09-20 16:36:01

标签: php laravel foreign-keys

我想创建动态大型菜单,但是当我正在建立表格关系时,我会收到错误。请让我知道如何建立关系。

表格结构如下: -

1)类别

id整数

类别varchar

2)子类别

id整数

子类别varchar

category_id整数

3)parentcategories

id整数

parentname varchar

subcategory_id整数

模型

Categories.php

protected $table = "categories";
public function sub(){
    return $this->hasManyThrough(Subcategories::class,Parentcategories::class,'subcategory_id','category_id');
}

Subcategories.php

protected $table = "subcategories";
public function category()
{
    return $this->belongsTo('App\Categories');
}

Parentcategories.php

protected $table = "parentcategories";
public function subcategory()
{
    return $this->belongsTo('App\Subcategories');
}

PagesController.php

public function index(){
    $categories = Categories::all();
    return view('pages.home')->with('categories',$categories);
}

刀片模板

      @foreach($categories as $category)
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
          {{ $category->category }} <i class="fa fa-chevron-down" 
          aria-hidden="true"></i>
        </a>
        <ul class="mega-menu dropdown-menu">
          @foreach($category->sub->take(20) as $subcategory)
            <li class="col-sm-3">
              <h5>{{$subcategory->subcategory}} <i class="fa fa-caret-right" aria-hidden="true"></i></h5>
              <ul class="mega-list">
                <li><a href="#">parent categories comes here</a></li>
              </ul>
            </li>
          @endforeach
        </ul>
      </li>
      @endforeach

由于

1 个答案:

答案 0 :(得分:0)

正如我可以看到你的表是层次结构是以simillar方式,我想这可以用单表完成。创建一个名为categories的表,并按照下面的表结构:

navigation table

现在创建一个模型 Category.php :类似这样的东西:

<?php

class Category extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'categories';

    public function parent() {

        return $this->hasOne('category', 'id', 'parent_id');

    }

    public function children() {

        return $this->hasMany('category', 'parent_id', 'id');

    }  

    public static function tree() {

        return static::with(implode('.', array_fill(0, 4, 'children')))->where('parent_id', '=', NULL)->get();

    }

}

现在在你的控制器中假设 HomeController.php 写:

<?php

class HomeController extends BaseController {

    protected $layout = "layouts.main";

    public function showWelcome()
    {

        $items = Category::tree();

        $this->layout->content = View::make('layouts.home.index')->withItems($items);

    }

}

在视图中假设 index.blade.php ,您可以像这样传递:

<ul>
    @foreach($items as $item)
        <li>{{ $item->title }}
            @foreach($item['children'] as $child)
            <li>{{ $child->title }}</li>
            @endforeach
        </li>
    @endforeach
</ul>

这适用于层次结构的n-number,更高效和单个表类别,希望这有帮助