拉拉威尔-自我参照关系不起作用



我使用Laravel 8在我的数据库中,我有一个菜单表,其中包含以下数据:

id  | id_parent | name         | route                 | routename            | term   | active
----------------------------------------------------------------------------------------
1   | NULL      | "Home"       | "/"                   | "home"               | "main" | 1
2   | NULL      | "Storage"    | "/storage"            | "storage"            | "main" | 1
3   | 2         | "Devices"    | "/storage/devices"    | "storage.devices"    | "main" | 1
4   | 2         | "New Device" | "/storage/new-device" | "storage.new-device" | "main" | 1

在我的菜单模型中,我有这样的代码:

public function parent()
{
return $this->belongsTo('AppModelsMenu', 'id_parent');
}
public function children()
{
return $this->hasMany('AppModelsMenu', 'id_parent');
}

我的控制器中的功能如下:

static function getMenu($term)
{
$id_userrole = Auth::user()->id_userrole;
$route = Request::route()->getName();
$menu = Menu::select('name','route','routename')
->with('children')
->where([['term',$term], ['active',1],['id_parent',null]])
->whereHas('access', function($q) use ($id_userrole) {
$q->where('id_userrole', $id_userrole)
->orWhere('id_userrole', 0);
})
->get();
dump($menu);
foreach($menu as &$m) {
$m->isActive = $route == $m->routename ? 1 : 0;

foreach($m->children as &$m2) {
$m2->isActive = $route == $m2->routename ? 1 : 0;
$m->isActive = $m2->isActive;
}
}

return ApiResource::collection($menu);
}

如果我想得到孩子,数组是空的。这是我的输出:

{"data":[{"name":"Home","route":"/","routename":"home","isActive":0,"children":[]},{"name":"Storage","route":"/storage","routename":"storage","isActive":0,"children":[]}]}

我做错了什么?

如果模型结果有id列,则children关系将起作用,您可以这样测试:

Menu::with('children')->all();

BTW,parent关系应为:

public function parent()
{
return $this->belongsTo('AppModelsMenu', 'id', 'id_parent');
}

如果你想得到孩子们的孩子。。。

public function descendants()
{
return $this->children()->with('descendants');
}

相关内容

  • 没有找到相关文章

最新更新