【问题标题】:show comment data on post laravel在 laravel 帖子上显示评论数据
【发布时间】:2018-09-20 03:50:53
【问题描述】:

所以昨天我成功统计了帖子中的评论,现在我想在管理仪表板中显示评论,所以这是我在控制器中的代码

public function getComment()
{
    $user = Auth::user();
    $posts = $user->posts();

    foreach ($posts as $key => $value) {
        $posts[$key]->post_comments = PostComment::where('post_id', $value->id)->get(); 
    }
    return $posts;
}

这是我获取此评论的 web.php 路由代码

Route::get('/comment/post/{id}', 'DashboardController@getComment');

但即使在不同的帖子中,它也会检索所有评论,我只想从我想要的同一帖子中获得评论。奇怪的是,当我单击按钮时,它会从帖子中检索随机 id 而不是 id,它看起来像这样

http://127.0.0.1:8000/comment/post/%7Bid%7D

希望大家能帮帮我,谢谢

【问题讨论】:

  • 你想检索某个帖子的所有cmets,不是吗?。
  • 是的,兄弟
  • github.com/sapna-bhayal/post_comment在这里你会找到完整的解决方案
  • @AyamGeprek 检查我的答案https://stackoverflow.com/a/52418428/2876362

标签: php json laravel controller eloquent


【解决方案1】:

Laravel中我们可以使用关系来获取相关数据。这是获取用户发布 cmets 的示例:-

public function getComment()
{
    $userId = Auth::user()->id;
    $posts = Post::where('user_id', $userId)->with("post_comments")->get();
    return $posts;
}

Post模型中你需要添加这个

use App\Comment;

public function post_comments()
{
    return $this->hasMany(Comment::class);
}

我希望这将帮助您以一种简单的方式解决您的问题。

【讨论】:

    【解决方案2】:

    这里是通过 post->id 检索某个帖子的所有 cmets 的代码

    public function getComment($id) {
        $comments = Comment::query()->where('post_id', $id)->get();
        return $comments;
    }
    

    确保 Comment 模型类具有表名

    【讨论】:

    • 还是不明白
    【解决方案3】:

    我编辑了我的代码并得到了这个解决方案,我在 get comment 参数上添加了 id

        public function getComment($id)
    {
        $user = Auth::user();
        $posts = $user->posts();
    
        foreach ($posts as $key => $value) {
            $posts[$key]->post_comments = PostComment::where('post_id', $id)->get(); 
        }
        return $posts;
    }
    

    【讨论】:

    • 检查我的答案。这不是获取帖子 cmets 的正确方法。
    【解决方案4】:
    public function getComment($id) {
        $results = Post::with(['comments'])->where('post_id',$id);
        $posts = $results->get();
    }
    

    Post.php

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Post extends Model {
    
        public function comments() {
            return $this->hasMany(Comment::class, 'post_id');
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-14
      • 2019-12-07
      • 1970-01-01
      • 2022-01-10
      • 2016-11-07
      • 2021-11-02
      • 2017-02-11
      • 2018-10-21
      • 2015-05-24
      相关资源
      最近更新 更多