我想从表中的用户名信息Users
与笔者id
从表S = Pages
。为此,我做了一个foreach
循环并将数据添加到users
数组中。
这会获取数据,但格式不正确,无法在刀片模板中使用。下面是代码:
$pages = \App\page::all();
$users = array();
foreach ($pages as $page) {
$user = \App\user::where('id', $page->author)->get('name');
$users[] = $user;
}
dd($users);
return view('admin.pages', compact('pages', 'users'));
我已经用dd($users)
方法转储了结果并得到了这个:
我在刀片模板中使用此代码进行检索,但在该$users[$loop->index]->get('name')
位置得到空白。
@foreach ($pages as $page)
<tr>
<th>{{ $page->id }}</th>
<th>{{ $page->title }}</th>
<th>{{ $users[$loop->index]->get('name') }}</th>
@if($page->status = 'ACTIVE')
<th><span class="label label-success">{{ $page->status }} </span></th>
@elseif($page->status = 'DRAFT')
<th><span class="label label-warning">{{ $page->status }} </span></th>
@endif
<th>{{ $page->Actions }}</th>
</tr>
@endforeach
您没有正确定义您的关系。App\User
应该在模型中定义以下内容:
public function pages()
{
// have to specify the key name is author, not user_id
return $this->hasMany("App\Page", "author");
}
然后在App\Page
模型中,您将具有以下内容:
public function pageauthor()
{
// have to specify the key name is author, not user_id
return $this->belongsTo("App\User", "author");
}
然后在您的Blade模板中,您只需引用$page->author->name
:
@foreach ($pages as $page)
<tr>
<th>{{ $page->id }}</th>
<th>{{ $page->title }}</th>
<th>{{ $page->pageauthor->name }}</th>
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句