Laravel 5 获取其他数据 table

Laravel 5 get data other table

我有下一个结构:table menus(id, title, type, parent_id, page_id) 和 页面(id,别名标题,内容) 模型菜单

class Menu extends Model
{

    public function parent()
    {
        return $this->belongsTo('App\Menu', 'parent_id');
    }

    public function children()
    {
        return $this->hasMany('App\Menu', 'parent_id');
    }

    public function page()
    {
        return $this->belongsTo('App\Page', 'page_id');
    }

}

I want get the next result:
-Item 1 (show name menu table)
-Item 2
  -Subitem 1 and alias (show name **menu** table and show alias **page** table)
  -Subitem 2 and alias
-Item 3
  - Suitem 1 and alias

Eloquent查询

$items = Menu::with(['children' => function($query){
            $query->with('page');
        }])->where(['parent_id' => null])->get(); 

查看

@foreach($items as $item)
    @if($item->children()->count() > 0)
            @foreach($item->children as $child)
                <li><a href="/page/">{{$child->title}}</a></li>
            @endforeach
    @else 
      <li><a href="/page/{{$item->page->alias}}">{{$item->title}}
@endforeach

如何获取嵌套在 foreach 中的别名页面?

您可以使用:

{{ $child->page->alias }} 

显示子菜单页面别名,假设每个子项都有 page

否则你可以使用:

{{ optional($child->page)->alias }}

如果您是 运行 Laravel 5.5 或:

{{ $child->page ? $child->page->alias : '' }}

如果你 运行 Laravel < 5.5

您还可以改进预加载和代码:

$items = Menu::with('children.page', 'page')->whereNull('parent_id')->get();