在laravel上显示评论数据

时间:2018-09-20 03:50:53

标签: php json laravel controller eloquent

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

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

希望你们能帮我谢谢

4 个答案:

答案 0 :(得分:2)

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

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

发布模型中,您需要添加

use App\Comment;

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

我希望这可以帮助您轻松解决问题。

答案 1 :(得分:0)

这是通过post-> id

检索特定帖子的所有评论的代码
public function getComment($id) {
    $comments = Comment::query()->where('post_id', $id)->get();
    return $comments;
}

确保Comment模型类具有表名

答案 2 :(得分:0)

我编辑了代码并获得了解决方案,我在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;
}

答案 3 :(得分:0)

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

}