首页 > 解决方案 > Laravel 的 belongsTo 关系返回空对象

问题描述

post.php

class post extends Model
{
   use HasFactory;
   public function publisher()
   {
       return $this->belongsTo('App\Models\User');
   }
   protected $fillable = ['title','image','price','Describtion','image1','image2','image3','image4','publisher'];
    
}

Fetchpost.php

class Fetchpost extends Component
{
   use WithPagination;

   public function render()
   {
       return view('livewire.fetchpost', ['posts' => post::orderBy('created_at', 'desc')->paginate(10)],);
   }
}

fetchpost.blade.php

<div>
    @foreach($posts as post)
        <img class="rounded" src="{{ $post->publisher->profile_photo_path }}">
        <h1>{{ $post->publisher }}</h1>
        <h3>{{ $post->title }}</h1>
        <p>{{ $post->Description }}</p>
    @endforeach
</div>

所以我想要实现的是显示发布者个人资料信息的帖子,如姓名和个人资料照片(如 facebook),但我收到错误

试图获取非对象的属性“profile_photo_path”

标签: phplaravel

解决方案


这里的问题是,您没有在关系中明确传递外键。因此,使用关系定义的命名约定,laravel 正在您的 post 表中寻找一个publisher_id(关系方法名称_父表的主键)列。但是没有,因为您的外键publisher只有并且 laravel 无法建立关系。因此,您在尝试获取非对象的属性时遇到错误。在关系中引用外键是一个好习惯。或使用 laravel 约定制作外键。

public function publisher()
{
    return $this->belongsTo('App\Models\User', 'publisher');
}

推荐阅读