【发布时间】:2021-06-04 18:09:01
【问题描述】:
我正在使用 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();
});
}
【问题讨论】:
-
你能把你的
queations迁移文件放上去吗? -
@Droid 是的,我有
-
@Droid 我刚刚添加了我的
users表的捕获。 -
试试 {{ $show->users}} ,分享结果
-
@lagbox 你救了我的命,非常感谢你:)