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

时间:2018-08-14 20:06:19

标签: laravel collections php-carbon

我正在尝试输出一个created_at集合,以便于人们对JSON请求可读。

以下代码有效:

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

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

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

我已经尝试过了:

 返回$ childComments-> map(function($ childComments){

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

});
 

并抛出此错误。

  

{消息:“找不到两位数的月份↵数据丢失”,异常:“ InvalidArgumentException”,…}   例外   :   “ InvalidArgumentException”   文件   :   “ /Applications/MAMP/htdocs/community/vendor/nesbot/carbon/src/Carbon/Carbon.php”

编辑访问器尝试:

控制器

 返回$ childComments->每个(函数($ childComments){

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

});
 

评论模型

 公共函数getHumanDate()
{
    返回$ this-> created_at-> diffForHumans();
}
 

我现在在JSON输出中的所有created_at日期上都为空。

1 个答案:

答案 0 :(得分:1)

更正:雄辩地将时间戳记字段与Carbon对象之间进行转换。差异无法解析为新的Carbon对象。

一个简单的解决方案是将该字段重命名为created_diff之类的内容,这样模型就不会尝试解析它。

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

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();
});