【问题标题】:Call to undefined function App\belongsToMany [Laravel]调用未定义的函数 App\belongsToMany [Laravel]
【发布时间】:2015-11-29 06:05:01
【问题描述】:

我得到的错误是“调用未定义的函数 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)->reviews;但是,我无法运行 App\Review::find(1)->categories;它说“调用未定义的函数 App\BelongsToMany”

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    您的 categories() 方法中有两个错误。

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

    第一个错误是箭头。你输入了$this-belongsToMany,但它应该是$this-&gt;belongsToMany

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

    总而言之,方法应该是:

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

    【讨论】:

    • 哇,在那个箭头中丢失了 1 天:) 现在可以正常工作了。顺便说一句,我有一个问题,迁移的方法 index() 是做什么的?
    • 它添加了一个基本索引。有这个 stackoverflow 线程可以回答索引是如何工作的:stackoverflow.com/questions/3567981/how-do-mysql-indexes-work
    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 2018-10-16
    • 1970-01-01
    • 2020-01-10
    • 2018-02-02
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多