文章目录

  • 前言
  • model->created_at 为啥是 Carbon对象
  • model->toArray()['created_at'] 为啥是国际标准时间
  • 可以通过重写 serializeDate 来转换toArray返回的时间格式(Y-m-d H:i:s)

前言

        model->created_at 是 Illuminate\Support\Carbon 对象model->toArray()['created_at'] 是字符串(国际标准时间)

model->created_at 为啥是 Carbon对象

  1. model->created_at 触发魔术方法 __get()
namespace Illuminate\Database\Eloquent;use ArrayAccess;
use Illuminate\Contracts\Broadcasting\HasBroadcastChannel;
use Illuminate\Contracts\Queue\QueueableCollection;
use Illuminate\Contracts\Queue\QueueableEntity;
use Illuminate\Contracts\Routing\UrlRoutable;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\CanBeEscapedWhenCastToString;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Database\ConnectionResolverInterface as Resolver;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\Concerns\AsPivot;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection as BaseCollection;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\ForwardsCalls;
use JsonSerializable;
use LogicException;abstract class Model implements Arrayable, ArrayAccess, CanBeEscapedWhenCastToString, HasBroadcastChannel, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
{use Concerns\HasAttributes,Concerns\HasEvents,Concerns\HasGlobalScopes,Concerns\HasRelationships,Concerns\HasTimestamps,Concerns\HidesAttributes,Concerns\GuardsAttributes,ForwardsCalls;public function __get($key){return $this->getAttribute($key);}
}

2.调用 HasAttributes的getAttribute方法,getAttributeValue方法 取得value值

  • 判断模型timestamps属性,false 返回原始value
  • 然后判断字段key是否在模型的static::CREATED_AT | static::UPDATED_AT
  • 这两个值默认是 create_at | updated_at 可以通过模型重新设置这两个属性
  • 在的话就使用transformModelValue将 value转换成 Carbon 对象
namespace Illuminate\Database\Eloquent\Concerns;use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use DateTimeInterface;
use Illuminate\Contracts\Database\Eloquent\Castable;
use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Eloquent\Casts\AsArrayObject;
use Illuminate\Database\Eloquent\Casts\AsCollection;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\InvalidCastException;
use Illuminate\Database\Eloquent\JsonEncodingException;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\LazyLoadingViolationException;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection as BaseCollection;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;
use InvalidArgumentException;
use LogicException;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;trait HasAttributes
{public function getAttribute($key){if (! $key) {return;}// If the attribute exists in the attribute array or has a "get" mutator we will// get the attribute's value. Otherwise, we will proceed as if the developers// are asking for a relationship's value. This covers both types of values.if (array_key_exists($key, $this->attributes) ||array_key_exists($key, $this->casts) ||$this->hasGetMutator($key) ||$this->hasAttributeMutator($key) ||$this->isClassCastable($key)) {return $this->getAttributeValue($key);}// Here we will determine if the model base class itself contains this given key// since we don't want to treat any of those methods as relationships because// they are all intended as helper methods and none of these are relations.if (method_exists(self::class, $key)) {return;}return $this->getRelationValue($key);}public function getAttributeValue($key){return $this->transformModelValue($key, $this->getAttributeFromArray($key));}protected function transformModelValue($key, $value){// If the attribute has a get mutator, we will call that then return what// it returns as the value, which is useful for transforming values on// retrieval from the model to a form that is more useful for usage.if ($this->hasGetMutator($key)) {return $this->mutateAttribute($key, $value);} elseif ($this->hasAttributeGetMutator($key)) {return $this->mutateAttributeMarkedAttribute($key, $value);}// If the attribute exists within the cast array, we will convert it to// an appropriate native PHP type dependent upon the associated value// given with the key in the pair. Dayle made this comment line up.if ($this->hasCast($key)) {return $this->castAttribute($key, $value);}// If the attribute is listed as a date, we will convert it to a DateTime// instance on retrieval, which makes it quite convenient to work with// date fields without having to create a mutator for each property.# 主要看这里if ($value !== null&& \in_array($key, $this->getDates(), false)) {return $this->asDateTime($value);}return $value;}public function getDates(){if (! $this->usesTimestamps()) {return $this->dates;}$defaults = [$this->getCreatedAtColumn(),$this->getUpdatedAtColumn(),];return array_unique(array_merge($this->dates, $defaults));}public function getDates(){if (! $this->usesTimestamps()) {return $this->dates;}$defaults = [$this->getCreatedAtColumn(),$this->getUpdatedAtColumn(),];return array_unique(array_merge($this->dates, $defaults));}protected function asDateTime($value){// If this value is already a Carbon instance, we shall just return it as is.// This prevents us having to re-instantiate a Carbon instance when we know// it already is one, which wouldn't be fulfilled by the DateTime check.if ($value instanceof CarbonInterface) {return Date::instance($value);}// If the value is already a DateTime instance, we will just skip the rest of// these checks since they will be a waste of time, and hinder performance// when checking the field. We will just return the DateTime right away.if ($value instanceof DateTimeInterface) {return Date::parse($value->format('Y-m-d H:i:s.u'), $value->getTimezone());}// If this value is an integer, we will assume it is a UNIX timestamp's value// and format a Carbon object from this timestamp. This allows flexibility// when defining your date fields as they might be UNIX timestamps here.if (is_numeric($value)) {return Date::createFromTimestamp($value);}// If the value is in simply year, month, day format, we will instantiate the// Carbon instances from that format. Again, this provides for simple date// fields on the database, while still supporting Carbonized conversion.if ($this->isStandardDateFormat($value)) {return Date::instance(Carbon::createFromFormat('Y-m-d', $value)->startOfDay());}$format = $this->getDateFormat();// Finally, we will just assume this date is in the format used by default on// the database connection and use that format to create the Carbon object// that is returned back out to the developers after we convert it here.try {$date = Date::createFromFormat($format, $value);} catch (InvalidArgumentException $e) {$date = false;}return $date ?: Date::parse($value);}
}

model->toArray()[‘created_at’] 为啥是国际标准时间

1.toArray() 调用了 Illuminate/Database/Eloquent/Concerns/HasAttributes.php 的 attributesToArray方法
2.attributesToArray 调用 addDateAttributesToArray

  • addDateAttributesToArray 中判断 判断模型timestamps属性,false 跳过处理
  • 判断 key 是否在 static::CREATED_AT | static::UPDATED_AT中,不在 跳过处理
  • 将value处理成Carbon对象

3.通过serializeDate(Carbon) 将Carbon处理成国际标准时间

可以通过重写 serializeDate 来转换toArray返回的时间格式(Y-m-d H:i:s)

namespace App\Models\Auth;use App\Models\Traits\RichSoftDeletes;
use DateTimeInterface;class User extends \Illuminate\Database\Eloquent\Model
{use RichSoftDeletes;protected $fillable = ['name', 'mobile', 'password', 'creator', 'updater'];protected $hidden = ['mobile'];protected $casts = ['id' => 'string','creator' => 'boolean',];public function toArray(){$res = parent::toArray();$values = array_values($res);$keys = array_keys($res);$keys = array_map(function ($key) {return ucfirst($key);}, $keys);return array_combine($keys, $values);}public function serializeDate(DateTimeInterface $date){return $date->format('Y-m-d H:i:s');}
}

Laravel的created_at与deleted_at 类型相关推荐

  1. laravel中的ORM模型修改created_at,updated_at,deleted_at三个时间字段类型

    laravel框架中的ORM模型极大的简化了数据库操作,同时也提高了数据操作安全性. 在laravel框架ORM模型中默认会有三个时间字段,created_at,updated_at,deleted_ ...

  2. Laravel Passport里的授权类型介绍

    本文来自pilishen.com----原文链接; 欢迎来和pilishen一起学习php&Laravel:学习群:109256050 OAuth2是一个安全框架,控制着程序受保护部分的准入, ...

  3. Php Laravel框架 多表关系处理 之 Eloquent一对多关系处理

    Php Laravel框架 多表关系处理 之 Eloquent一对多关系处理 本博文主要介绍 Laravel 框架中 Eloquent  对一对多关系的处理以及在 Laravel Administra ...

  4. 最棒的 7 个 Laravel admin 后台管理系统推荐 - 卡拉云

    本文完整版:<最棒的 7 个 Laravel admin 后台管理系统推荐> 目录 Laravel admin 后台管理系按类型选择 脚手架型 CRUD 接口型 可视化编程 新一代低代码开 ...

  5. gorm软删除_Gorm.Model.DeletedAt 变量类型分析

    以下介绍基于 Golang 语言的操作 Gorm 介绍 Gorm 是处理 Mysql 的一个工具.默认使用 struct `Name` 对应的 `Name`s 作为表名,同时 struct 参数名,作 ...

  6. 财务数据mysql库设计_数据库设计规范 - MySQL

    数据库设计规范 表达是与否概念的字段,必须使用 is_xxx的方式命名,数据类型是 unsigned tinyint( 1表示是,0表示否) 任何字段如果为非负数,必须是 unsigned. 表名.字 ...

  7. mysql 保存索引 create schema_【Schema】结构生成器 - Schema Builder

    介绍 Laravel 的结构生成器 (Schema) 提供一个与数据库无关的数据表产生方法,它可以很好的处理 Laravel 支持的各种数据库类型,并且在不同系统间提供一致性的 API 操作. 建立与 ...

  8. Nova: 虚机的块设备总结 [Nova Instance Block Device]

    和物理机一样,虚拟机包括几个重要的部分:CPU.内存.磁盘设备.网络设备等.本文将简要总结虚机磁盘设备有关知识. 1. Nova boot CLI 中有关虚机块设备的几个参数 nova boot CL ...

  9. sequelize模型关联_Node.js Sequelize 模型(表)之间的关联及关系模型的操作

    Sequelize模型之间存在关联关系,这些关系代表了数据库中对应表之间的主/外键关系.基于模型关系可以实现关联表之间的连接查询.更新.删除等操作.本文将通过一个示例,介绍模型的定义,创建模型关联关系 ...

最新文章

  1. 计算机为什么找不到c盘d盘,电脑不显示是什么盘?是C盘还是D盘?怎么才能显示出来呢?...
  2. Java 8 - 收集器Collectors_分组groupingBy
  3. iar烧录程序步骤_STM8入门以及程序编译、烧录、IAR使用方法(扫盲篇...
  4. python xpath提取转码_python-xpath获取html文档的部分内容
  5. [转载] JAVA8 创建流的5种方式
  6. python __init__.py的作用是什么?
  7. 使用Arduino和超声波传感器实现简单测距
  8. 合并数字 — m个数字消除相邻的差的绝对值为1的两个数中较大的那一个,直到没有两个相邻的差的绝对值为 1 的数(动态数组定义)
  9. Codefroces 762A k-th divisor 数论
  10. Maven打包时报Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war解决方案
  11. Eclipse 使用的注意 灵格斯 取词
  12. Lua 包管理 - Luarocks 使用指南
  13. python找色_python坐标找色
  14. react —— 解决报错之 Objects are not valid as a React child (found: [object HTMLDivElement]). If you meant
  15. Android 在一个APP里打开另一个APP
  16. curl: (51)Unable to communicate securely with peer
  17. Android文档管理器
  18. 百万数据进行查询与排序
  19. 基于网络的入侵检测数据集研究综述(A Survey of Network-based Intrusion Detection Data Sets)
  20. doraemon with latex

热门文章

  1. Java学习笔记(9)-数组
  2. c# 串口通信 DataReceived 事件触发方法的使用
  3. hdu-5643 King's Game(打表)
  4. php riak,Riak的分布式数据库模型 - 分布式数据库相关理论 Part3
  5. 十进制转k进制 k进制转十进制
  6. 在存储过程中调用execute immediate 执行 create table语句报TBR-17004: Permission denied
  7. 海乐淘商城系统--01前缀(功能介绍以及关于架构)
  8. .NET Core2.0 WebApi 接收模型对象参数为Null
  9. 数字IC后端实现TOP Floorplan专家秘籍
  10. 极路由系列 刷机方法