LARAVEL Eloquent:将帖子链接到用户然后用户链接到个人资料

时间:2018-03-18 18:10:03

标签: php laravel eloquent table-relationships laravel-5.6

我的目标是检索用户图像(来自个人资料表列'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

2 个答案:

答案 0 :(得分:0)

您的主视图中似乎存在一些问题。请使用此代码再试一次,然后看看。

主页视图

@if(count($posts) > 0)
@foreach($posts as $post)
<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

您甚至可以通过运行您的控制器

这样的雄辩模型查询来进一步避免作者的n + 1问题
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class MainController extends Controller
{
  public function index() {
  $posts = Post::with("author")->paginate(9);

return view('pages.home')->with('posts', $posts);
}

我希望这会有所帮助。

答案 1 :(得分:0)

在您的控制器索引方法中尝试使用:

public function index() {
  $posts = Post::with("author.profile")->paginate(9);

  return view('pages.home')->with('posts', $posts);
}

更新帖子模型关系:

public function author()
{
    return $this->belongsTo('App\User', 'user_id'); // update to users table foreign key
}