php - Laravel 8:试图获取非对象错误的属性“名称”
问题描述
我正在使用 Laravel 8 开发我的论坛项目。所以我创建了一个名为 的表answers
,这里是它的迁移:
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();
});
}
然后为了建立Question
模型和Answer
模型之间的关系,我添加了这些:
问题.php:
public function answers()
{
return $this->hasMany(Answer::class);
}
用户.php:
public function answers()
{
return $this->hasMany(Answer::class);
}
之后,我添加了这个来显示问题信息:
@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
但现在我得到这个错误:
ErrorException 试图获取非对象的属性“名称”
那么这里出了什么问题呢?如何正确返回提出问题的用户的姓名?
如果您对此有任何想法或建议,我将不胜感激,
谢谢。
更新#1:
更新#2:
class Answer extends Model
{
protected $fillable = ['answer', 'user_id', 'question_id'];
}
解决方案
您应该在 Answer 模型中建立 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);
}
}
在您的刀片中,假设 $ans 是 Answer 模型的一个实例,您可以使用:
{{ $ans->user->name }}
推荐阅读
- python - 使用基于多个百分位条件的数据在熊猫中创建新列
- go - 单例实例不断在 Go 中创建新实例
- css - 如何根据子级高度调整固定高度的父级 div?
- matlab - 如何在 Matlab 中使用带有棋盘图像的相机校准来获得以毫米为单位的像素大小?
- jekyll - Jekyll 站点帖子和液体命令连接错误
- socket.io - 套接字 io CORS 被阻止
- plotly-dash - 如何在不使用字典的情况下更新数据表行
- benchmarking - 用于测量速度和内存消耗的与语言无关的基准测试工具
- google-sheets - 从 Google 电子表格获取动态范围
- haskell - 如何从类型中获取价值