【问题标题】:How to override all time attributes如何覆盖所有时间属性
【发布时间】:2016-08-06 15:39:21
【问题描述】:

在我的模型中,我有设置和获取时间属性的函数,像这样

  public function setEndTimeAttribute($value)
  {
    return $this->attributes['end_time'] = date("H:i", strtotime($value));
  }
  public function getEndTimeAttribute($value)
  {
    return date("h:i a", strtotime($value));
  }
  public function setStartTimeAttribute($value)
  {
    return $this->attributes['start_time'] = date("H:i", strtotime($value));
  }
  public function getStartTimeAttribute($value)
  {
    return date("h:i a", strtotime($value));
  }

我这样做是因为 MySQL 以某种方式需要格式,我想以不同的格式向我的用户显示它。我需要为所有时间输入执行此操作。

我可以继续为我的模型中的每个属性创建这些 get/set 函数,但我希望有人可以向我揭示一种更好的方法,我只需要这样做一次。在我看来,我的做法是错误的。

【问题讨论】:

    标签: mysql laravel datetime laravel-4


    【解决方案1】:

    您应该考虑利用 laravel 开箱即用的出色 Carbon

    在您的模型中,将您希望作为 Carbon 实例返回的任何字段添加到 $dates 数组:

    protected $dates = ['created_at', 'updated_at', 'custom_field'];
    

    现在,当您调用模型时,它会自动返回一个 Carbon 实例并允许您执行以下操作:

    // In your controller
    ...
    $user = App\User::find($id);
    
    return view('user', compact('user'));
    ...
    
    // Then in your view 
    <p> Joined {{ $user->created_at->diffForHumans(); }} </p>
    
    // output
    Joined 8 days ago
    

    【讨论】:

      【解决方案2】:

      没有简单的方法可以对多个字段的访问器/修改器进行分组。 Laravel 在访问它们时调用它们,这通过获取或设置基于每个属性发生。

      但是,如果您的模型中有很多具有相似名称(start_time、end_time)的属性,您可能需要考虑使用特征。这样,您只需在模型中使用 trait,您就可以将所有逻辑放在一个位置。

      例子:

      use Carbon\Carbon;
      
      trait TimeFieldsTrait
      {
          public function formatDisplayTime($value)
          {
              return Carbon::parse($value)->format('h:i a');
          }
      
          public function formatDbTime($value)
          {
              return Carbon::parse($value)->format('H:i');
          }
      
          public function setEndTimeAttribute($value)
          {
              return $this->attributes['end_time'] = $this->formatDbTime($value);
          }
      
          public function getEndTimeAttribute($value)
          {
              return $this->formatDisplayTime($value);
          }
      
          public function setStartTimeAttribute($value)
          {
              return $this->attributes['start_time'] = $this->formatDbTime($value);
          }
      
          public function getStartTimeAttribute($value)
          {
              return $this->formatDisplayTime($value);
          }
      }
      

      而在您的模型中,您只需使用该特征...

      class YourModel extends Model
      {
          use TimeFieldsTrait;
      }
      

      【讨论】:

        猜你喜欢
        • 2020-07-17
        • 1970-01-01
        • 2016-07-29
        • 2011-11-06
        • 2020-02-13
        • 1970-01-01
        • 2015-01-08
        • 2013-12-16
        • 1970-01-01
        相关资源
        最近更新 更多