我有一个函数,当单击显示帖子按钮时,它会检索帖子的所有评论。然后使用 Javascript 显示评论,我想做的是向数组添加一个键值对,这将告诉我的 javascript 评论所有者是否是登录用户,从而允许我添加编辑和删除按钮该用户的帖子。
这可能是也可能不是进行这种比较的最佳方式,但这是我在无限缺乏经验的情况下制定的一种方式,所以我可以使用 javascript 来显示注释并允许编辑/删除注释。我知道我可以向数据库表添加一个列my_posts并将其保留为空,然后使用 array_push 向此字段添加适当的值,但我在这里尝试过的方法可能吗?
我的函数在这里:
public function postGetComments(Request $request) {
$post = $request['postid'];
$comments = DB::table('comments')
->join('users', 'users.id', '=', 'comments.user_id')
->select('comments.*', 'users.username')
->where('post_id', '=', $post)
->orderby('created_at', 'desc')
->get()
;
foreach ($comments->get() as $comment) {
$user = Auth::user();
if ($user->id == $comment->user_id) {
$comment['my_post'] = 'true';
} else {
$comment['my_post'] = 'false';
}
}
return response()->json(['commentsForPost' => $comments]);
}
我收到一个错误,因为最后我的 foreach 循环有问题。如果没有此循环,查询将按设计检索并显示所有注释。我对 Laravel(使用 5.2)很陌生,我想知道我在尝试将密钥my_post、将comments.user_id与 user.id 进行比较并将值 true/false 适当地添加到数组时做错了什么?谢谢!
您已经在$comments查询上运行了 get() 方法。将你的 foreach 循环更改为此
foreach ($comments as $comment) {
$user = Auth::user();
if ($user->id == $comment->user_id) {
$comment['my_post'] = 'true';
} else {
$comment['my_post'] = 'false';
}
}