首页 > 解决方案 > 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);
}

标签: laravel

解决方案


你应该这个

public function comments()
{
 return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
}

在你的控制器中

$post = \App\Post::find(1);
$comments = $post->comments;

推荐阅读