Laravel模型属性$dates作用是什么?
1). 当前使用的 Laravel 版本?
Laravel8
今天看到模型$date属性,搜索了一下,网上说他的作用是:里面所包含的字段,就是当使用这个属性的时候,可以直接后面跟着carbon类时间操作的任何方法。
然后我自己试着验证一下,我有个模型如下:
<?php
/**
* Created by Reliese Model.
*/
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserTrip extends Model
{
protected $table = 'user_trip';
protected $dates = [
'created_at',
'updated_at'
];
}
然后我在控制器查询打印:
$trip = UserTrip::where(['id' => 2])
->select(["*"])
->first();
var_dump($trip->created_at);
echo $trip->created_at->getTimestamp();
打印结果:
object(Illuminate\Support\Carbon)#310 (19) {
["endOfTime":protected]=>
bool(false)
["startOfTime":protected]=>
bool(false)
["constructedObjectId":protected]=>
string(32) "000000000a76bc7c0000000031c40a50"
["localMonthsOverflow":protected]=>
NULL
["localYearsOverflow":protected]=>
NULL
["localStrictModeEnabled":protected]=>
NULL
["localHumanDiffOptions":protected]=>
NULL
["localToStringFormat":protected]=>
NULL
["localSerializer":protected]=>
NULL
["localMacros":protected]=>
NULL
["localGenericMacros":protected]=>
NULL
["localFormatFunction":protected]=>
NULL
["localTranslator":protected]=>
NULL
["dumpProperties":protected]=>
array(3) {
[0]=>
string(4) "date"
[1]=>
string(13) "timezone_type"
[2]=>
string(8) "timezone"
}
["dumpLocale":protected]=>
NULL
["dumpDateProperties":protected]=>
NULL
["date"]=>
string(26) "2022-04-27 11:17:10.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Asia/Shanghai"
}
1651029430
说明确实是一个Carbon对象,然后我把模型的$date数组里的updated_at去掉,再次执行控制器代码
发现结果一样,还是Carbon对象:
object(Illuminate\Support\Carbon)#310 (19) {
["endOfTime":protected]=>
bool(false)
["startOfTime":protected]=>
bool(false)
["constructedObjectId":protected]=>
string(32) "00000000236533c0000000006c7d0566"
["localMonthsOverflow":protected]=>
NULL
["localYearsOverflow":protected]=>
NULL
["localStrictModeEnabled":protected]=>
NULL
["localHumanDiffOptions":protected]=>
NULL
["localToStringFormat":protected]=>
NULL
["localSerializer":protected]=>
NULL
["localMacros":protected]=>
NULL
["localGenericMacros":protected]=>
NULL
["localFormatFunction":protected]=>
NULL
["localTranslator":protected]=>
NULL
["dumpProperties":protected]=>
array(3) {
[0]=>
string(4) "date"
[1]=>
string(13) "timezone_type"
[2]=>
string(8) "timezone"
}
["dumpLocale":protected]=>
NULL
["dumpDateProperties":protected]=>
NULL
["date"]=>
string(26) "2022-04-27 11:17:10.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Asia/Shanghai"
}
1651029430
所以我搞不明白这个属性是干嘛的了?
好像发现问题了,这2个字段在MySQL里面是datetime类型的,改为其他比如timestamp,去掉updated_at之后就报错了,因为他不是carbon对象。
刚刚又验证了下,如果我新增一个字段test_time,不管他是datetime类型还是timestamp类型,在$dates数组配就是carbon对象,不在就不是。所以个人认为是框架默认对created_at,updated_at转为carbon对象,其他字段要自定义【比如上面的test_time,要想让他是carbon对象,就要放到$dates数组】
本作品采用《CC 协议》,转载必须注明作者和本文链接
可以把 这两个字段改成自定义
就相当于自定义的时间字段设置后可以用carbon包装后返回来直接用carbon自带的方法