所以昨天我成功地计算了帖子中的评论,现在我想在管理仪表板中显示评论,所以这是我在控制器中的代码
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,它看起来像这样
希望你们能帮我谢谢
答案 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');
}
}