【问题标题】:Laravel 5.2 Invalid argument supplied for foreach()Laravel 5.2 为 foreach() 提供的参数无效
【发布时间】:2017-11-11 07:51:49
【问题描述】:

我试图从两个数据库表中显示我的数据,但我收到错误消息为 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

这是我的评论表

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');
     }

【问题讨论】:

    标签: php laravel laravel-5 foreach laravel-5.2


    【解决方案1】:

    belongsTo() 定义的关系只返回一个对象,而不是一个集合。这就是为什么您不能使用 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

    【讨论】:

    • 兄弟,当我将belongsTo更改为hasMany时,然后创建一个新错误(1)Column not found: 1054 Unknown column 'cmets.post_model_id' in 'where Clause'(SQL:select count() 作为来自comments 的聚合,其中comments.post_model_id = 1 和comments.post_model_id 不为空)(视图:E:\Project\htdocs\lara_blog\resources\views\blog\single. blade.php) (2)Column not found: 1054 Unknown column 'cmets.post_model_id' in 'where clause' (SQL: select count() as aggregate from comments where comments.post_model_id = 1 和comments.post_model_id 不为空)
    • 那是因为您的外键名称与模型名称不匹配 - 为什么需要该模型后缀?无论如何,我已经更新了答案
    • 对不起兄弟,这条消息显示给我。感谢您的反馈。声望低于 15 人的投票会被记录,但不会改变公示显示的帖子分数。
    • 投票和标记为已回答是两件事 - 因为您是提问者,所以您可以将问题标记为已回答。在此处查看详细信息:stackoverflow.com/help/someone-answers
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2016-10-09
    • 2018-12-09
    • 1970-01-01
    • 2015-06-29
    • 2022-01-27
    • 2018-02-26
    相关资源
    最近更新 更多