laravel - Laravel:“试图获取非对象的属性'评论'”
问题描述
我为 post 模型设置了一个 api 资源集合,称为 PostCollection。我对帖子的评论查询有问题。获取 $comments 的非对象。评论表目前没有记录。
$author = \App\Post::find(1);
$comments = \App\Post::find(1)->comments;
return [
'id' => $this->id,
'user_id' => $this->user_id,
'description' => $this->description,
'media' => $this->media,
'media_type' => $this->media_type,
'likes' => $this->likes,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'author_avatar' => $author->setting->user_profile_photo,
'author_profile_name' => $author->name,
'author_user_name' => $author->setting->user_name,
'visible' => true,
'comments' => $comments,
];
在后模型中,我有:
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
在评论模型中,我有:
public function user()
{
return $this->belongsTo(User::class);
}
public function post()
{
return $this->belongsTo(Post::class);
}
解决方案
你应该这个
public function comments()
{
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
}
在你的控制器中
$post = \App\Post::find(1);
$comments = $post->comments;
推荐阅读
- flutter - 如何在 VideoPlayerController.file().initialize().whenComplete() 之前返回一个小部件;完成了吗?
- node.js - 为什么我有 TypeError: Cannot read property '1' of null with GET REST API?
- excel - Excel宏:处理一系列值的一般原理
- python - 在 Python 中创建替换字典
- python - 具有两个未知数的两个同余系统的解(两个同余具有相同的模数)
- python - 如何将列表拆分为包含 3 个元素的多个列表?
- python-3.x - 以自动有组织的方式将资产负债表从 SEC 导入 Dataframe
- javascript - 标记单击时打开错误的弹出窗口
- sql - 如何在关系数据库设计中处理空列
- reflection - 骆驼在aggregationStrategy处访问prevRouteContext