php - 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”
解决方案
这里的问题是,您没有在关系中明确传递外键。因此,使用关系定义的命名约定,laravel 正在您的 post 表中寻找一个publisher_id
(关系方法名称_父表的主键)列。但是没有,因为您的外键publisher
只有并且 laravel 无法建立关系。因此,您在尝试获取非对象的属性时遇到错误。在关系中引用外键是一个好习惯。或使用 laravel 约定制作外键。
public function publisher()
{
return $this->belongsTo('App\Models\User', 'publisher');
}
推荐阅读
- wpf - XamDataGrid 如何在字段中添加鼠标右键单击操作?(基础设施)
- python - plt.show() 不显示数据,而是将其保留用于下一个绘图(spyder)
- java - 在数组中的列和行中查找最大数
- mongodb - Windows Mongodb 插入测试密钥并将其删除以监控连接
- vue.js - 覆盖子组件中的道具类型?
- javascript - 通过另一个页面发布表单数据
- python-3.x - SKLearn 分类器带有 class_weight 参数
- python - django中基于类别的列表视图
- google-api - 尝试更改 API 配置时收到“提交失败”错误
- python - 从 Python io.BufferedReader 类的实例读取/打开图像