调用未定义的函数App \ belongsToMany [Laravel]

时间:2015-11-29 06:05:01

标签: php laravel laravel-5 eloquent

我得到的错误是"调用未定义的函数App \ belongsToMany"。

这是用于关系的两种模型之一:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Review extends Model
{
protected $table = "reviews";

protected $fillable = [ 'user_id','email','review'];

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

public function votes()
{
    return $this->belongsToMany('App\User')->withPivot('vote')->withTimestamps();
}

public function categories()
{
    return $this-belongsToMany('Category','category_review','review_id','category_id')->withTimestamps();
}

public function tags()
{
    return $this->belongsToMany('App\Tag')->withTimestamps();
}

}

我的其他模特:

<?php

 namespace App;

 use Illuminate\Database\Eloquent\Model;

 class Category extends Model
 {
public function reviews()
{
    return $this->belongsToMany('App\Review','category_review','category_id','review_id')->withTimestamps();
}

public function children()
{
    return $this->hasMany('App\Category','parent_id');
}

public function parent()
{
    return $this->belongsTo('App\Category','parent_id');
}

}

问题是,我可以运行App \ Category :: find(1) - &gt; reviews;但是,我无法运行App \ Review :: find(1) - &gt;类别;它说&#34;调用未定义的函数App \ BelongsToMany&#34;

1 个答案:

答案 0 :(得分:0)

categories()方法中有两处错误。

public function categories()
{
    return $this-belongsToMany('Category','category_review','review_id','category_id')->withTimestamps();
}

第一个错误是箭头。您放置了$this-belongsToMany但它应该是$this->belongsToMany

第二个错误是命名空间。它应该是App\Category

总之,方法应该是:

public function categories()
{
    return $this->belongsToMany('App\Category','category_review','review_id','category_id')->withTimestamps();
}