Laravel 5获取其他表数据 [英] Laravel 5 get data other table
本文介绍了Laravel 5获取其他表数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下一个结构:表格菜单(id,标题,类型,parent_id,page_id)和 页数(id,别名,内容) 模型菜单
I have the next stucture: table menus(id, title, type, parent_id, page_id) and pages(id, alias title,content) Model Menu
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
口语查询
$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中?
How get alias page nested in foreach ?
推荐答案
您可以使用:
{{ $child->page->alias }}
以显示子菜单页面别名,假设每个孩子都有page
.
to display child menu page alias assuming you have page
for each child.
否则,您可以使用:
{{ optional($child->page)->alias }}
如果您正在运行Laravel 5.5或:
if you are running Laravel 5.5 or:
{{ $child->page ? $child->page->alias : '' }}
如果您正在运行Laravel< 5.5
if you are running Laravel < 5.5
此外,您可以改善急切的加载并编写一些代码:
Also you could improve eager loading and code a bit:
$items = Menu::with('children.page', 'page')->whereNull('parent_id')->get();
这篇关于Laravel 5获取其他表数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文