Laravel- 5.5 App\Comment :: user必须返回一个关系实例.

3 php one-to-many laravel laravel-5.5

我想展示产品评论.但是,当我这样做时,它给了我上面的错误.我该如何解决这个问题?

我正在使用一对多的关系beetwen product-commentsuser-comments

产品型号;

 public function comments(){
        return $this->hasMany('App\Comment','product_id','id');
    }
Run Code Online (Sandbox Code Playgroud)

用户模型;

public function comments() {

         return $this->hasMany('App\Comment','user_id','id');
     }
Run Code Online (Sandbox Code Playgroud)

评论模型;

public function user(){

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

    public function product(){
        $this->belongsTo('App\Product');
    }
Run Code Online (Sandbox Code Playgroud)

刀片文件

<figcaption class="text-center">{{$comment->user->username}}</figcaption>
Run Code Online (Sandbox Code Playgroud)

Ale*_*nin 6

你需要回归关系.所以添加returnuser()关系定义方法:

public function user()
{
    return $this->belongsTo('App\User');
}
Run Code Online (Sandbox Code Playgroud)

同样是与product()关系:

public function product()
{
    return $this->belongsTo('App\Product');
}
Run Code Online (Sandbox Code Playgroud)