【问题标题】:How do I post comments under posts in Laravel?如何在 Laravel 的帖子下发表评论?
【发布时间】:2020-02-09 07:24:45
【问题描述】:

我有一个方法,可以将评论添加到数据库中。对于每个帖子,自己的评论。我的带有表单的刀片页面有一个隐藏的输入,来自女巫我的 id 帖子

<input type="hidden" value="{{ $post->post_id }}" name="post_id">

我的方法

public function store(Request $request)
{
    $comment = new Music_comment();
    $comment->comment = $request->comment;
    $comment->author_id = \Auth::user()->id;
    $comment->post_id = (int)$request->input('post_id');

    $comment->save();

    return redirect()->back()->with('success', 'Комментарий добавлен');    
}

但是我无法获取帖子下的 cmets,需要在每个帖子下显示与帖子 ID 对应的已定义评论。我的视图作曲家方法:

View::composer('*', function($music) {
        $music->with(['post_comment' => Music_comment::orderBy('created_at', 'desc')->limit(4)->get()]);
    });

【问题讨论】:

    标签: laravel


    【解决方案1】:

    如果您应该在Music_comment 模型和Post 上显示模型关系,那就太好了。假设您已经正确定义了关系,您可以这样做。

    View::composer('*', function($music) {
            $music->with(['post.comment' => function($query){
                    $query->orderBy('created_at', 'desc')->limit(4);
            };
        });
    

    希望这会有所帮助。

    附言

    如果你想检索经过身份验证的用户的 id 你可以这样做Auth::id()

    【讨论】:

      【解决方案2】:

      你可以用 laravel 雄辩的关系来处理它。
      1) 在您的 Music 模型上添加此功能。

      public function comments() {
              return $this->hasMany(Comment::class, 'id', 'post_id');
             //here id is parent id, post_id is child id which is in comments table
          }
      

      2) 在 laravel Blade 上/在您的控制器 *function 上使用此代码直接访问您的所有评论

       $comments =  $music->comments(); 
      

      或者,

      $comments =  $music->comments()->orderBy('created_at', 'desc')->limit(4)->get()
      

      for one-to-many relationship guide click this link

      【讨论】:

        猜你喜欢
        • 2017-02-11
        • 2017-07-29
        • 2014-05-10
        • 1970-01-01
        • 1970-01-01
        • 2018-07-17
        • 2017-07-07
        • 1970-01-01
        • 2020-07-07
        相关资源
        最近更新 更多