Laravel 5.2 为 foreach() 提供的参数无效

Laravel 5.2 Invalid argument supplied for foreach()

我试图显示来自两个数据库 table 的数据,但我收到错误消息 Invalid argument supplied for foreach()。任何人都知道我如何解决这个获取错误?

注意:我是 laravel

的新人

这是我的控制器:

$post = PostModel::find($post_id);
$comment = new CommentModel;

我的 PostModel:

public function comments() {
    return $this->belongsTo('App\CommentModel');
}

我的评论模型:

 public function post() {
         return $this->belongsTo('App\PostModel');
    }

我想在其中显示我的数据库模型的视图页面:

 @foreach($post->comments as $comment)  
<div class="comment"> 
    <div class="author-info">
        <div class="author-name">
            <h4>{{ $comment->name }}</h4>
        </div>      
    </div>      
    <div class="comment-content">
        {{ $comment->comment }}     
    </div>  
</div>
@endforeach

这是我的评论table

public function up() 
{
    Schema::create('comments', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email');
    $table->text('comment');
    $table->boolean('approved');
    $table->integer('post_id')->unsigned();
    $table->timestamps();
  });

    Schema::table('comments', function ($table){
          $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
         });
     }


     public function down()
     {
         Schema::dropForeign(['post_id']);
         Schema::drop('comments');
     }

belongsTo() returns 定义的关系只有一个对象,不是集合。这就是为什么你不能用 foreach.

迭代它的原因

替换

public function comments() {
  return $this->belongsTo('App\CommentModel');
}

public function comments() {
  return $this->hasMany('App\CommentModel', 'post_id');
}

您可以在此处详细了解如何使用 Eloquent 定义不同类型的关系:https://laravel.com/docs/5.2/eloquent-relationships