无法在laravel中获取帖子视图中的评论用户数据

问题描述 投票:-1回答:2

我有三个模型和相应的表。用户,帖子,评论。用户表的列是ID,名称,电子邮件。帖子表的列是ID,标题,正文。评论表的列是id,user_id,post_id,评论。

用户模型具有以下功能:

public function comments(){

        return $this->hasMany('App\Comment');
    }

帖子模型具有以下功能:

public function comments(){

        return $this->hasMany('App\Comment');
    }

注释模型具有以下两个功能:

 public function user(){

        $this->belongsTo('App\User');
    }

    public function post(){

        $this->belongsTo('App\Post');
    }

显示PostController中函数的单个帖子如下:

public function show($slug)
    {
        $post = Post::where('slug', $slug)->first();
        return view('post.show')->withPost($post);
    }

并且在show.blade.php中,我正在尝试实现此功能:

@foreach($post->comments as $comment)
<p>
{{$comment->user->name}}
 </p>
@endforeach

为什么抛出错误,说关系方法必须返回一个对象?

php laravel-5.2 one-to-many
2个回答
1
投票

您需要return关系,所以您的代码成为:

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

public function post(){
    return $this->belongsTo('App\Post');
}

-2
投票

那么bathmate泵是什么?

访问:https://bathmatehydromaxshop.com

© www.soinside.com 2019 - 2024. All rights reserved.