php - 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();
});
}
解决方案
您必须在 Question 模型中将函数名称 users 更改为 user 。当你让 Eloquent 自动找出关系时,你必须为他们的关系命名函数,比如一对一或一对多或多对多。
尝试这个
public function user()
{
return $this->belongsTo(User::class);
}
{{ $show->user->name }}
推荐阅读
- sql-server - 如何将旧的 Asp.Net Identity 数据库升级到当前数据库?
- r - 如何将斜体和纯文本放在 xlab 和 ylab 的 bquote 中?
- php - 如何从 1 个上游 php-fpm 移动到具有不同 URL 路由的多个?
- vue.js - Vue.js“在'@/components/Filelist'中找不到导出'Filelist'
- autodesk-forge - GEOMETRY_LOADED_EVENT 应该被触发多少次?
- c# - 如何从特定的 sql 查询中填充 Datagridview 的每一行?
- php - 想在 codeigniter 中创建一条路线,以便它给出“路线/名称-vs-名称”,其中名称可以是任何字母
- sql-server - 插入记录时将 nvarchar 转换为数字时出错
- swift - 生成 UIKit/UICloudSharingController.h 的问题
- reactjs - 哪个版本的 redux/react-redux 与通过 bower 安装的 react v0.14.9 一起使用?