php Laravel 5 查询关系导致“调用成员函数 addEagerConstraints() on null”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31546081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:30:30  来源:igfitidea点击:

Laravel 5 Querying with relations causes "Call to a member function addEagerConstraints() on null" error

phpmysqllaravellaravel-5eloquent

提问by Tomkarho

I have been trying to create a simple user management system but keep on hitting road blocks when it comes to querying relations. For example I have usersand rolesand whenever I try to make a query for all users and their roles I get an error. The one in the title is only the latest one I've encountered.

我一直在尝试创建一个简单的用户管理系统,但在查询关系时一直遇到障碍。例如,我有用户角色,每当我尝试查询所有用户及其角色时,我都会收到错误消息。标题中的那个只是我遇到的最新一个。

My User and Role Models look like this:

我的用户和角色模型如下所示:

class Role extends Model
{
    public function users()
    {
        $this->belongsToMany('\App\User', 'fk_role_user', 'role_id', 'user_id');
    }
}


class User extends Model
{
    public function roles()
    {
        $this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
    }
}

My migration table for many-to-many relationship between the two looks like this:

我的两者之间多对多关系的迁移表如下所示:

public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->nullable(); //fk => users
            $table->integer('role_id')->unsigned()->nullable(); //fk => roles

            $table->foreign('fk_user_role')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('fk_role_user')->references('id')->on('roles')->onDelete('cascade');
        });
    }

And then I try to get all records with their relation in a controller:

然后我尝试在控制器中获取所有记录及其关系:

public function index()
{
    $users = User::with('roles')->get();

    return $users;
}

So I need another pair of eyes to tell me what is it I am missing here?

所以我需要另一双眼睛来告诉我我在这里错过了什么?

回答by jedrzej.kurylo

You are missing returnstatements in the methods that define relations. They need to return relation definition.

您在定义关系的方法中缺少return语句。他们需要返回关系定义。

Replace

代替

public function roles()
{
    $this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
}

With

public function roles()
{
    return $this->belongsToMany('\App\Role', 'role_user', 'user_id', 'role_id');
}