【发布时间】:2018-03-18 18:10:02
【问题描述】:
我的目标是检索用户图像(来自个人资料表列“profile_img”)并显示在每个帖子的页脚上。
我可以使用$post->author->name 检索作者姓名,使用$post->author->profile->profile_image 检索个人资料图片,但它仅在我有一条记录(帖子)时才有效。当有多个记录时,我收到一个错误尝试获取非对象的属性“配置文件”(查看:xampp/......./home.blade.php)
谁能告诉我哪里出错了??
型号:
用户
public function post()
{
return $this->hasMany('App\Post');
}
public function profile()
{
return $this->hasOne('App\Profile');
}
简介
public function user()
{
return $this->belongsTo('App\User');
}
发帖
public function author()
{
return $this->belongsTo('App\User', 'id');
}
控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class MainController extends Controller
{
public function index() {
$posts = Post::paginate(9);
return view('pages.home')->with('posts', $posts);
}
主页视图
@if(count($posts) > 0)
@foreach($posts as$posts)
<div>
<div class="post-title"><h3>{{$post->title}}</h3></div>
<div class="post-description">
{!!mb_substr($post>body,10,rand(35,40)) !!} ....
</div>
<div class="featured-details">
<div class="p-clearfix">
<img class="authorimg"src="/storage/profile_images/{{ $post->author->profile->profile_image }}">
<div class="author-title lite">{{ $post->author->name }}</div>
<div class="lite thumbnail-date">{{ date('M j, Y', strtotime($post->created_at)) }}</div>
</div>
</div>
</div>
<hr>
@endforeach
@else
no post yet
@endif
【问题讨论】:
标签: php laravel eloquent table-relationships laravel-5.6