首页 文章

将集合中的created_at值更改为人类可读的碳

提问于
浏览
0

我正在尝试输出一个集合created_at时间,以便人类可以读取JSON请求 .

以下代码有效:

$childComments = $comment->getParentsChildren($comment->id , $childCount)->with('creator')->get();

return $childComments->map(function($childComments){
    return [
        'created_at' => $childComments->created_at->diffForHumans()
    ];
});

问题是只返回created_at,我想返回$ childComments集合的其余部分,而不必手动添加每个属性 .

我试过这个:

return $childComments->map(function($childComments){

    $childComments->created_at = $childComments->created_at->diffForHumans();

});

并抛出此错误 .

{message:“无法找到两位数月份数据丢失”,异常:“InvalidArgumentException”,...}异常:“InvalidArgumentException”文件:“/ Applications / MAMP / htdocs / community / vendor / nesbot / carbon / src /Carbon/Carbon.php”

Edit Accessor Attempt:

Controller

return $childComments->each(function($childComments){

    $childComments->created_at = $childComments->humanDate;

});

Comment Model

public function getHumanDate()
{
    return $this->created_at->diffForHumans();
}

我现在在JSON输出中的所有created_at日期都变为null .

1 回答

  • 1

    Correction: Eloquent将时间戳字段转换为Carbon对象和从Carbon对象转换时间戳字段 . diff无法解析为新的Carbon对象 .

    一个简单的解决方案就是将此字段重命名为 created_diff 之类,因此模型不会尝试解析它 .

    您还需要从map闭包中返回该对象,否则,该集合将只填充空值:

    return $childComments->map(function($childComments){
        $childComments->created_diff = $childComments->created_at->diffForHumans();
        return $childComments;
    });
    

    或者由于对象是可变的并通过引用传递,您也可以使用每个:

    return $childComments->each(function($childComments){
        $childComments->created_diff = $childComments->created_at->diffForHumans();
    });
    

相关问题