[英]Laravel 8: Trying to get property 'name' of non-object error
I'm working with Laravel 8 to develop my Forum project.我正在使用 Laravel 8 开发我的论坛项目。 So I created a table called
answers
, and here is the Migration for that:所以我创建了一个名为
answers
的表,这里是 Migration :
public function up()
{
Schema::create('answers', function (Blueprint $table) {
$table->id();
$table->text('answer');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('question_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
}
And then in order to make relation between Question
Model & Answer
Model, I added these:然后为了在
Question
Model 和Answer
Model 之间建立关系,我添加了这些:
Question.php: Question.php:
public function answers()
{
return $this->hasMany(Answer::class);
}
User.php:用户.php:
public function answers()
{
return $this->hasMany(Answer::class);
}
After that, I added this for showing the question information:之后,我添加了这个来显示问题信息:
@foreach($show->answers as $ans)
<table class="table table-striped table-bordered table-responsive-lg">
<thead class="thead-light">
<tr>
<th scope="col"></th>
<th scope="col">Answer</th>
</tr>
</thead>
<tbody>
<tr></tr>
<tr>
<td style="text-align:right">
<div><span>Writer: </span><a href="">{{ $ans->id->name }}</a></div>
</td>
<td style="text-align:right">
<p>
{{ $ans->answer }}
</p>
</td>
</tr>
</tbody>
</table>
@endforeach
But now I get this error:但现在我得到这个错误:
ErrorException Trying to get property 'name' of non-object ErrorException 试图获取非对象的属性“名称”
So what is going wrong here?那么这里出了什么问题呢? How can I properly return the name of user who asked a question?
如何正确返回提出问题的用户的姓名?
I would really appreciate if you share any idea or suggestion about this,如果您对此有任何想法或建议,我将不胜感激,
Thanks.谢谢。
UPDATE #1:更新#1:
UPDATE #2:更新#2:
class Answer extends Model
{
protected $fillable = ['answer', 'user_id', 'question_id'];
}
you should build the relation between Answer an User models in Answer model:您应该在 Answer model 中建立 Answer an User 模型之间的关系:
class Answer extends Model
{
protected $fillable = ['answer', 'user_id', 'question_id'];
public function user()
{
return $this->belongsTo(User::class);
}
public function question()
{
return $this->belongsTo(Question::class);
}
}
and in your blade, assuming that the $ans is an instance of Answer model, you can use:在您的刀片中,假设 $ans 是 Answer model 的一个实例,您可以使用:
{{ $ans->user->name }}
$table->foreign('user_id')->references('id')->on('users')->constrained()->onDelete('cascade');
$table->foreign('question_id')->references('id')->on('questions')->constrained()->onDelete('cascade');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.