在帖子拉拉维尔上显示评论数据



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

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

这是我的网络.php路线代码来获取此评论

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

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

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

希望你们能帮助我谢谢

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

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

后期模型中,您需要添加此

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

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

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

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

确保注释模型类具有表名

我编辑了我的代码并得到了这个解决方案,我在 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;
}
public function getComment($id) {
$results = Post::with(['comments'])->where('post_id',$id);
$posts = $results->get();
}

后.php

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

最新更新