Laravel 5使用关系查询会导致"在null上调用成员函数addEagerConstraints()"错误

Tom*_*rho 46 php mysql laravel eloquent laravel-5

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

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

class Role extends Model
{
    public function users()
    {
        $this->belongsToMany('\App\User', 'fk_role_user', 'role_id', 'user_id');
    }
}
Run Code Online (Sandbox Code Playgroud)
class User extends Model
{
    public function roles()
    {
        $this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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');
        });
    }
Run Code Online (Sandbox Code Playgroud)

然后我尝试在控制器中获取他们关系的所有记录:

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

    return $users;
}
Run Code Online (Sandbox Code Playgroud)

所以我需要另一双眼睛告诉我这里我缺少什么?

jed*_*ylo 148

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

更换

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

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

  • 我现在要自杀:P浪费时间,至少现在我永远不会忘记 (2认同)

小智 8

您需要使用 Return 来获取函数的结果。如果你不这样做,Laravel 不知道应该如何处理该函数而不需要任何操作。就这样使用

return $this->hasOne(xxx, xx, xx);
Run Code Online (Sandbox Code Playgroud)

享受你的编码吧!


小智 6

您忘记了函数中的返回

做:

return $this->belongsToMany('\App\User', 'fk_role_user', 'role_id', 'user_id');

return $this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');