我试图检索评论的created_at时间,目前我可以添加评论,它会显示时间,但刷新时间会消失。
提交时出现时间
在刷新时消失,因此需要在getPosts map方法中检索,但我不确定如何将其包含在内。
有人能指出正确的方向吗,我知道它必须对此做些什么
https://laravel.com/docs/5.5/collections
这就是我现在所拥有的。
PostController中
public function getPosts( )
{
$posts = Post::with('user')
->with(['likes' => function ($query) {
$query->whereNull('deleted_at');
$query->where('user_id', auth()->user()->id);
}])
->with(['comments' => function($query) {
$query->with('user');
}])
->get();
$data = $posts->map(function(Post $post, Comment $comment )
{
$user = auth()->user();
if($user->can('delete', $post)) {
$post['deletable'] = true;
}
if($user->can('update', $post)) {
$post['update'] = true;
}
$post['likedByMe'] = $post->likes->count() == 0 ? false : true;
$post['likesCount'] = Like::where('post_id', $post->id)->get()->count();
$post['createdAt'] = $post->created_at->diffForHumans();
$post['createdAt'] = $post->updated_at->diffForHumans();
// not getting the time for comments
$comment['comment_createdAt'] = $comment->created_at->diffForHumans();
return array($post, $comment);
});
return response()->json($data);
}
评论控制器
public function create(Request $request, $post)
{
$data = request()->validate([
'comment_body' => 'required|max:1000'
]);
$data['user_id'] = auth()->user()->id;
$data['name'] = auth()->user()->name;
$data['post_id'] = $post;
$post = Comment::create($data);
// sets a time on a comment instantly im using angular :)
$data['comment_createdAt'] = $post->created_at->diffForHumans();
$response = new Response(json_encode($data));
$response->headers->set('Content-Type', 'application/json');
if(!$response){
return 'something went wrong';
}
return response()->json($data);
}
HTML
<div ng-show="comments" id="comments" class="col-md-offset-2 animated fadeIn panel-default" ng-repeat="comment in post.comments">
<div style="font-size:10px;" id="eli-style-heading" class="panel-heading">
<a class="link_profile" href="/profile/<% comment.user.name | lowercase %>"><% comment.user.name %></a>
</div>
<figure class="my-comment">
<p> <% comment.comment_body%>
</p>
<p><% comment.comment_createdAt %> </p>
<hr>
</figure>
</div>
答案 0 :(得分:1)
回答你的问题:由于我认为帖子有很多评论,你不能只将帖子的创建日期分配给一个评论:
$post['comment_createdAt'] = $post->created_at->diffForHumans();
相反,您应该遍历所有注释并将日期存储在数组中。
但是这种方法有点麻烦,因为Comment对象已经保留了created_at
值。我只是检索日期并在前端格式化它:
<p><% comment.created_at | diffForHumans %> </p>
diffForHumans
是一个JS实现,您必须自己编写。
<强>更新强>:
模特评论:
class Comment
{
public function getCreatedAtAttribute($value)
{
return Carbon::createFromFormat($this->dateFormat, $value)
->diffForHumans();
}
}
<p><% comment.created_at %> </p>
但是这会在检索到的所有时间内转换created_at
日期。一种变体和更好的方法是使用自定义访问器:
class Comment
{
public function getCreatedAtHumanDiffedAttribute()
{
return Carbon::createFromFormat($this->dateFormat, $this->created_at)
->diffForHumans();
}
}
<p><% comment.created_at_human_diffed %> </p>
有关他们的更多信息here:
使用API Resources。你的用例完全是它们的用途。
老实说,您的代码存在问题。一些评论: