【问题标题】:Error when displaying data according to the id in the database根据数据库中的id显示数据时出错
【发布时间】:2020-07-19 13:12:15
【问题描述】:

我有一个问题,我不知道如何解决它,我有一个页面显示了一些问题,从数据库中获取,我做了一个 cmets 部分,我如何根据 post_id 获取 cmets?我试着把它们拿走,但它没有显示出来,我做了类似的事情:

路线::

Route::get('/viewUserQuestion/{post}', 'PostsController@viewUserQuestion')->name('viewQuestion');

控制器:

 public function viewUserQuestion(Post $post, Comment $comment) { return view('viewQuestion', compact('post'), compact('comment'));

只有当我有类似comment [0] -> commentText 时才会显示给我,如果我没有收到错误,建议我如何根据 id 获取它们?

架构::

        $table->id();
        $table->integer('post_id')->default();
        $table->integer('user_id');
        $table->text('commentText');
        $table->timestamps();
    });```

...

【问题讨论】:

    标签: php html mysql laravel


    【解决方案1】:

    首先,当您返回视图时,您没有正确地将变量传递给它

    return view(
        'viewQuestion', 
         compact('post'), 
         compact('comment')
    );
    

    这会将第三个参数传递给view() 方法,而不是将postcomment 作为单个数组的一部分。我建议阅读 compact() here 中的文档,以便更好地理解它的作用,但本质上它只是一个关联数组。

    你会想要做这样的事情:

    return view('viewQuestion', [ 
         'post' => $post
    ]);
    

    如果您的Post 模型与您的Comment 模型具有hasMany() 关系

    后模型

    /**
     * A Post has many Comments.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function comments()
    {
        return $this->hasMany(Comment::class, 'post_id');
    }
    

    您只需转到$post->comments即可访问所有cmets

    【讨论】:

      【解决方案2】:

      试试这个

      public function viewUserQuestion(Post $post) 
      { 
          $comment = Comment::where('post_id',$post->id)->get();
          return view('viewQuestion', compact('post','comment'));
      }
      

      或者改变路线。

         Route::get('/viewUserQuestion/{post}/{comment}', 'PostsController@viewUserQuestion')->name('viewQuestion');
      

      要使用此路由,还必须发送评论 id

      祝你好运

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多