laravel - 如何在 Laravel 的帖子下发表评论?
问题描述
我有一种方法,可以将评论添加到数据库中。对于每个帖子,自己的评论。我的带有表单的刀片页面有一个隐藏的输入,来自女巫,我接受了 id post
<input type="hidden" value="{{ $post->post_id }}" name="post_id">
我的方法
public function store(Request $request)
{
$comment = new Music_comment();
$comment->comment = $request->comment;
$comment->author_id = \Auth::user()->id;
$comment->post_id = (int)$request->input('post_id');
$comment->save();
return redirect()->back()->with('success', 'Комментарий добавлен');
}
但是我无法获取帖子下的评论,必须在每个帖子下显示与帖子ID相对应的定义评论。我的视图作曲家方法:
View::composer('*', function($music) {
$music->with(['post_comment' => Music_comment::orderBy('created_at', 'desc')->limit(4)->get()]);
});
解决方案
如果您应该在Music_comment
Model 和Post
它上显示模型关系,那就太好了。假设您已经正确定义了关系,您可以这样做。
View::composer('*', function($music) {
$music->with(['post.comment' => function($query){
$query->orderBy('created_at', 'desc')->limit(4);
};
});
希望这可以帮助。
附言
如果你想检索经过身份验证的用户的 id 你可以这样做Auth::id()
推荐阅读
- reactjs - 尝试将 socket.io 附加到节点服务器时出现 TypeError
- angular - 订阅不能设置公共变量
- gcc - ARM Cortex M 的 gcc 不支持 FPU?
- c++ - 将 HINTERNET 连接移到程序外
- paste - Tmux 3.0a 如何在 Ubuntu 20.0.4 下通过命令行
- pine-script - 如何在警报消息框中更改警报消息而不每次都更改它的代码或代码
- javascript - 窗口对象缺少函数
- csv - 在 TSV 和 TTL 文件中存储三元组有什么区别?
- css - 在 CSS 中隐藏标签
- css - aos.css 不适用于 django 后端网站