数据模型

数据模型

数据模型是软件的重要组成部分,基于场景化需求二次封装了 Model 模型。

  • 模型基类 app/Models/Model.php
    <?php
    namespace App\Models;
    use Illuminate\Database\Eloquent\Model as Eloquent;
    use App\Models\Traits\HasDateTimeFormatter;
    class Model extends Eloquent{
        use HasDateTimeFormatter;
        public $timestamps = false;
        protected $guarded=[];
    }
    
    
  • 时间序列化 app/Models/Traits/HasDateTimeFormatter.php
    <?php
    namespace App\Models\Traits;
    use DateTimeInterface;
    trait HasDateTimeFormatter{
        protected function serializeDate(DateTimeInterface $date){
            return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
        }
    }
    
  • 日期转换 app/Models/Casts/DateStamp.php
    <?php
    namespace App\Models\Casts;
    use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
    class DateStamp implements CastsAttributes{
        public function get($model, $key, $value, $attributes){
            return date("Y-m-d",$value);
        }
        public function set($model, $key, $value, $attributes){
            return strtotime($value);
        }
    }
    
  • 时间转换 app/Models/Casts/TimeStamp.php
    <?php
    namespace App\Models\Casts;
    use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
    class TimeStamp implements CastsAttributes{
        public function get($model, $key, $value, $attributes){
            return date("Y-m-d H:i:s",$value);
        }
        public function set($model, $key, $value, $attributes){
            return strtotime($value);
        }
    }
    
  • 示例模型
    <?php
    namespace App\Models;
    use App\Models\Casts\TimeStamp;
    class Log extends Model{
        protected $casts = [
            'time' => TimeStamp::class,
        ];
    }
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
搜索