donglin4636 2016-09-26 18:09
浏览 203
已采纳

laravel new列默认值created_at值

I have a table with orders like:

Order

id
created_at
shipped_at
billed_at

the shipped_at is on the packing list and the billed_at on the invoice.The fields shipped_at and billed_at are recently added.

When I create the order sometimes I want to give the created_at date a custom date if the order is for the future (i know this wasnt the original idea behind created_at). What I want is that the value of created_at is copied to shipped_at and billed_at on creation, because i sometimes use a custom value for created_at I cant just use current date time.

I can create an Order on 5 different locations so it would be nice if I could just create one function to copy these values instead of call the same function from 5 locations where i create an order.

Is there a clever location in the laravel framework to copy the value of created_at to shipped_at?

thoughts: Normaly I would think an event like saving would be best but the created_at is created after the save, is it possible to update/save in the saved event or would this create an infinit loop of saving?

  • 写回答

1条回答 默认 最新

  • dozr162106 2016-09-26 19:08
    关注

    Thanks to aynber comment to use the created event I came up with the following solution:

    in command line

    php artisan make:provider OrderDatesProvider
    

    to create a new provider. In the provider:

    <?php
    
    namespace App\Providers;
    
    use App\Order;
    use Illuminate\Support\ServiceProvider;
    
    class OrderDatesProvider extends ServiceProvider
    {
        /**
         * Bootstrap the application services.
         *
         * @return void
         */
        public function boot()
        {
    
            Order::created(function($order){
                $order->shipped_at = $order->created_at;
                $order->billed_at = $order->created_at;
                $order->save();
            });
    
        }
    
        /**
         * Register the application services.
         *
         * @return void
         */
        public function register()
        {
            //
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看