如何使用雄辩的关系列出类别,子类别,菜单

时间:2018-07-12 14:09:54

标签: php laravel eloquent

我已经开始学习Laravel并建立了雄辩的人际关系。我已经完成了“类别和子类别”的明智列表,但是现在我不知道如何在“类别和子类别”下显示菜单。

My Example:
----------
Category 1
  --Menu 1
  --Menu 2
  --Sub Category 1
    --Menu 3
Category 2
  --Menu 4
Category 3
    -- Sub Category 2
       --Menu 5

路线:

Route::get('/menus/list', 'API\UserController@getMenus');

UserController.php

<?php

namespace App\Http\Controllers\API;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\RoleUser;
use App\Articles;
use App\Menus;
use App\MainCategory;
use App\SubCategory;

class UserController extends Controller
{
    public function getMenus()
    {
        $categories = MainCategory::with('sub_category')->get();
        return $categories;
    }
}

MainCategory.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class MainCategory extends Model
{
    protected $table = 'main_category';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'parent_id', 'user_id', 'name', 'content'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [

    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function parent_category()
    {
        return $this->hasMany(self::class, 'id', 'parent_id');
    }


    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function sub_category()
    {
        return $this->hasMany(self::class, 'parent_id', 'id');
    }
}

Menus.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Menus extends Model
{
    protected $table = 'menus';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'category_id', 'name', 'content', 'created_at', 'status'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [

    ];
}

运行上述代码后,我得到以下结果:

[
  {
    "id": 1,
    "parent_id": null,
    "user_id": 1,
    "name": "Category 1",
    "content": "Maiores eligendi voluptates similique ullamco eum maxime et dicta temporibus sunt vel dicta labore temporibus",
    "status": 1,
    "sub_category": [

    ]
  },
  {
    "id": 2,
    "parent_id": null,
    "user_id": 1,
    "name": "Category 2",
    "content": "Quis quidem in in ut est adipisci pariatur Et sed odit",
    "status": 1,
    "sub_category": [
      {
        "id": 6,
        "parent_id": 2,
        "user_id": 1,
        "name": "Sub Category",
        "content": "Impedit voluptatum saepe commodo nulla sint voluptate consequatur Nihil autem",
        "status": 1
      }
    ]
  },
  {
    "id": 3,
    "parent_id": null,
    "user_id": 1,
    "name": "Category 3",
    "content": "Beatae voluptatibus excepturi qui harum ad aliquip laudantium molestiae reprehenderit esse",
    "status": 1,
    "sub_category": [

    ]
  },
  {
    "id": 4,
    "parent_id": null,
    "user_id": 2,
    "name": "Category 4",
    "content": "Ea tempor voluptate non ducimus et cillum nisi rem natus id voluptas laboriosam voluptatum voluptatibus tempor quo fugit",
    "status": 1,
    "sub_category": [

    ]
  },
  {
    "id": 6,
    "parent_id": 2,
    "user_id": 1,
    "name": "Sub Category",
    "content": "Impedit voluptatum saepe commodo nulla sint voluptate consequatur Nihil autem",
    "status": 1,
    "sub_category": [

    ]
  }
]

我的桌子:

enter image description here

enter image description here

任何想法如何实现菜单关系,因为我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

首先,您需要在Menus模型中定义与MainCategory模型的关系:

class MainCategory extends Model {
    ....

    public function menus() {
        return $this->hasMany('App\Menus', 'category_id', 'id');
    }

    ....
}

然后,由于您渴望加载sub_category,因此您还需要告诉Laravel加载其他关系,因为渴望加载只会返回该关系。有关急切加载(https://laravel.com/docs/5.6/eloquent-relationships#eager-loading)的更多信息,请参阅文档。

示例:

$categories = MainCategory::with('parent_category.menus', 'sub_category.menus')->get();

修改

由于您希望将菜单作为与parent_categorysub_category关系的关系来加载,因此您将需要直接从这些关系中调用菜单。

示例:

foreach ($categories as $category) {
    foreach ($category->parent_category as $parent) {
        foreach ($parent->menus as $menu) {
            //Do something with your menu
        }
    }
}

否则,如果您想直接将关系包括到$categories对象中(例如,通过$categories->menus进行调用),则需要更新您的急切负载以将菜单关系作为附加项包括在内论点。