3 回答

TA貢獻1816條經驗 獲得超4個贊
你沒有正確定義你的關系。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>
...

TA貢獻1866條經驗 獲得超5個贊
像這樣的東西應該可以幫助你
您的控制器
$pages = \App\page::all();
foreach ($pages as $page) {
$user = \App\user::find($page->author)->pluck('name');
if(isset($user)){
$page['user_name'] = $user->name;
} else {
$page['user_name'] = 'N/A';
}
}
return view('admin.pages', compact('pages'));
你的看法
@foreach ($pages as $page)
<tr>
<th>{{ $page->id }}</th>
<th>{{ $page->title }}</th>
<th>{{ $page->user_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
代碼與您當前的代碼有何不同
1) 它在主集合本身 ($pages) 中寫入用戶名,從而讓您不必擔心在視圖中只循環遍歷一個集合
2)它使用laravel,find()因為頁面只能有作者(我假設)(注意:find()基于您的主鍵工作,在這種情況下,它將搜索最常見的主鍵列id列)
3)它使用 pluck()
- 3 回答
- 0 關注
- 188 瀏覽
添加回答
舉報