【发布时间】:2020-02-02 17:37:04
【问题描述】:
我运行以下代码来显示我的一对多关系,但是我收到错误:Facade\Ignition\Exceptions\ViewException count():参数必须是数组或者实现了Countable的对象(查看:
这是我的代码:PostsController.php
public function show($id)
{
$post = Post::find($id);
$review = Post::find(1)->reviews()->where('title', 'posts_title')->first();
//$review = Review::all();
return view('posts.show', compact('post', 'review'));
}
Post.php
protected $tables='reviews';
function reviews(){
return $this->hasMany('App\Review', 'title', 'post_title');
}
从堆栈跟踪来看,错误就在这里:
@if(count($review) > 1)
@foreach($review as $reviews)
谁能帮忙?
【问题讨论】:
-
您正在尝试遍历
$review,但它是一个对象,因为您使用->first();获取它 -
你知道
first()、get()和all()之间的区别吗?
标签: laravel