如何在返回之前向数据库查询添加属性?

时间:2017-11-13 21:14:23

标签: php mysql database laravel eloquent

所以我有这样的事情:

$comments = Comments::select('id', 'topic', 'parent_id', 'username', 'comment', 'upvotes', 'created_at', 'updated_at')
        ->where('topic', '=', $topic)
        ->get();

// I'd like to add a human readable datetime difference like
// 1 day ago, 2 days ago, etc. before I return the $comments variable here.

return json_encode($comments);

对于单行我会做这样的事情:

$comment->created_at->diffForHumans();

如何为所有行添加额外属性,例如carbon_date?

1 个答案:

答案 0 :(得分:0)

循环遍历$comments数组并将属性添加到每个元素。

foreach ($comments as $comment) {
    $comment->carbon_date = $comment->created_at->diffForHumans();
}