首页 > 解决方案 > Laravel 8:试图获取非对象的属性“名称”

问题描述

我正在使用 Laravel 8 创建一个论坛。我想返回一个问题并显示提出此问题的用户的姓名。

User.php我编码的模型中:

public function questions()
    {
        return $this->hasMany(Question::class);
    }

我也把它放在Question.php模型上:

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

因此,为了获得提出问题的用户的姓名,我输入以下内容:

{{ $show->users->name }}

但现在我收到此错误消息:

试图获取非对象的属性“名称”**

那么这里出了什么问题?我该如何解决这个问题?

注意这个$show变量来自这个Controller Method并获取问题信息:

public function showQuestion($slug)
    {
        $show = Question::where('slug', $slug)->first();

        if(is_null($show)){
            abort(404);
        }

        return view('questions.question',[
            'show' => $show
        ]);
    }

并且每个问题都存储了user_id提出此问题的用户的信息:

捕获

因此,如果您对此有任何想法或建议,请告诉我,我将非常感激!

更新#1:

这是表格users

在此处输入图像描述

更新#2:

questions表迁移:

Schema::create('questions', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('title');
            $table->string('slug');
            $table->text('body');
            $table->string('category');
            $table->string('private')->nullable();
            $table->timestamps();
        });

users表迁移:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('phone')->unique();
            $table->binary('image')->nullable();
            $table->string('job')->nullable();
            $table->string('location')->nullable();
            $table->string('bio')->nullable();
            $table->string('skills')->nullable();
            $table->string('stackoverflow')->nullable();
            $table->string('github')->nullable();
            $table->string('instagram')->nullable();
            $table->string('linkedin')->nullable();
            $table->string('website')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

标签: phplaravellaravel-8

解决方案


您必须在 Question 模型中将函数名称 users 更改为 user 。当你让 Eloquent 自动找出关系时,你必须为他们的关系命名函数,比如一对一或一对多或多对多。

尝试这个

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


{{ $show->user->name }}

推荐阅读