【问题标题】:Laravel 8: Trying to get property 'name' of non-object on One To Many RelationshipLaravel 8:尝试在一对多关系上获取非对象的属性“名称”
【发布时间】:2021-05-09 22:23:59
【问题描述】:

我正在使用 Laravel 8 开发我的项目,在这个项目中,我在用户模型和角色模型之间应用了 OneToMany 关系,如下所示:

User.php:

public function role()
    {
        return $this->belongsTo(User::class);
    }

Role.php:

public function users()
    {
        return $this->hasMany(Role::class);
    }

现在我想编辑用户,所以在edit.blade.php,我添加了这一行来获取用户拥有的角色的名称:

<option selected="selected">{{ $user->role->name }}</option>

请注意,我已经在 edit 方法处压缩了user

public function edit(User $user)
    {
        return view('admin.users.edit', compact('user'));
    }

目前所有用户都有一个角色ID。

但现在我得到了这个错误:

试图获取非对象的属性“名称”(查看:edit.blade.php)

那么这里有什么问题?如何获取用户拥有的角色名称?

如果你想看的话,这也是roles 表的迁移:

public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
    }

这是add_fk_to_users_table迁移:

public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->unsignedBigInteger('role_id')->nullable()->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
        });
    }

我非常感谢你们对此提出的任何想法或建议......

提前致谢。

【问题讨论】:

    标签: php laravel relational-database one-to-many laravel-8


    【解决方案1】:

    你的User.php应该是这样的:

    public function role()
    {
        return $this->belongsTo(Role::class);// <--- this was your mistake. "Role" is correct!
    }
    

    还有Role.php:

    public function users()
    {
        return $this->hasMany(User::class); // <--- class should be "User" not "Role" here.
    }
    

    【讨论】:

    • 如果有帮助,请点击接受按钮。 :)
    猜你喜欢
    • 2020-09-28
    • 2021-06-04
    • 2021-07-10
    • 2021-06-05
    • 2021-07-29
    • 2014-03-25
    • 2019-12-13
    • 2015-06-03
    • 2017-02-22
    相关资源
    最近更新 更多