douya5331 2017-01-06 09:25
浏览 51
已采纳

从数据库中检索碳日期

   $rankArray = [
        'ranks' => $product[0]['productSalesRank']->pluck('rank'),
        'dates' => $product[0]['productSalesRank']->pluck('created_at')
    ];


    $rankArray['dates']->transform(function ($item) {
        return $item->format('d-m-Y');
    });

Having to transform everytime I retrieve the created_at/updated_at date from the database seems so inefficient, is there a simplier way of doing this?

I want to keep the date as Carbon, but in some instances, do just want the "value"

  • 写回答

3条回答 默认 最新

  • duanjie1339 2017-01-06 09:41
    关注

    Set a getter in your productSalesRank's Model(?) that does all the work for readying your dates.

    Model:

    class ProductSalesRank extends Model
    {
       protected $dates = ['created_at', 'updated_at']; 
       // whatever other columns you want to use Carbon on ^.
    
       public function getCreatedAtHumanAttribute() {
           return $this->created_at->format('d-m-Y');
       }
    }
    

    View/Controller/Wherever:

    $productSalesRank->created_at_human;  // will print it like you defined it in the model.
    

    Why _human?

    Sometimes later in the code you will find yourself needing the Carbon features on the created_at value. When you use format(), it returns a string, stripped out of Carbon features.


    [Update]

    Earlier we created a getter/accessor. As far as I know, you can't pass a variable like:

    ->created_at_human('mm') because it isn't a method, it is an accessor.

    In your Model, create a function.

    public function myFunction($format) {
       return $this->created_at->format($format);
    }
    

    In your view, simple:

    $productSalesRank->myFunction('d-m-Y');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: