我的帖子和评论之间有以下关系:
在 Post 模型中:
public function comments()
{
return $this->hasMany('App\Comment', 'post_id');
}
在评论模型中:
public function posts()
{
return $this->belongsTo('App\Post', 'id'); // id is the primary key in posts table
}
帖子在下面的 foreach 循环中返回没有任何问题,但每当我尝试使用关系来带来评论时,我都会看到以下错误:
foreach:
@foreach($topans as $topanswer)
<p> {{$topanswer->body}} </p>
<br>
@if(!empty($topanswer->comments))
@foreach($topans->comments as $topanscom)
<p>{{$topanscom->comment}} </p>
@endforeach
@endif
@endforeach
错误:
Undefined property: Illuminate\Database\Eloquent\Collection::$comments (View: C:\xampp\htdocs\sharp\resources\views\showPost.blade.php)
我错过了什么吗?
最佳答案
看起来您正试图在您的内部 foreach 循环中提取整个集合的答案。顶级集合 ($topans
) 是 topanswers 的集合,并且没有字段 comments
,因为它是一个集合。
尝试在内部 foreach 循环中提取第二级 topanswer
的注释:
@foreach($topanswer->comments as $topanscom)
此外,作为旁注,我认为您已经陷入命名的陷阱 - 使用更具描述性或不同的名称可能会有所帮助,这会帮助您摆脱麻烦:)
关于php - 尝试在 Laravel 中使用关系时出现未定义的属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59655746/