如何解决如何在 Laravel 中将时间戳转换为 unix 时间戳?
SO 伟大的人们你好
希望你们都有美好的一天!
我的项目时间戳有问题
我有 2 个模型,News
和 Comments
在我的项目工作期间,我试图复制“真实世界的数据”
所以在我的 Seeder (NewsSeeder
) 中,
use Faker\Generator as Faker;
use App\News;
...
public function run(Faker $faker) {
News::create([
'source' => $faker->url
'body' => $faker->paragraphs(random_int(1,4),true)
]):
}
// Please note that,relationship between `News` and `Comments` is `hasMany`
// `News` hasMany `Comment`
// `Comment` belongs to a `User`
在我的CommentSeeder
use Faker\Generator as Faker;
use App\News;
use App\Comment;
use App\User;
use Carbon\Carbon;
...
public function run() {
foreach (News::all() as $news) {
$i = 0;
for ($i; $i < random_int(1,5); $i++) { // This will generate comments for each `News` with random amount
$news->comments()->create([
'user_id' => User::inRandomOrder()->first()->id,'body' => $faker->paragraphs(random_int(1,3),true),'created_at' => Carbon::parse($news->created_at)->addMinutes(random_int(1,999)) // Comments created after the news is posted,make sense right?
]);
}
}
}
一切都像我想要的那样完美
问题是:我看到 2 个时间戳格式
示例:
"news": [
{
"source": ...
"body": ...
"created_at": "2021-02-10 15:19:09" // This
"comments": [
{
"user_id": ...
"body": ...
"created_at": "2021-02-10T16:22:33.000000Z" // and this
},...
...
]
},...
]
第一季度:
为什么它们不同?
在模型中我使用 $table->timestamps();
,这是 Laravel 的默认时间戳格式
第 2 季度:
如何让我所有的模型时间戳变成这样:“2021-02-10T08:22:33.000000Z”
提前致谢
如果有任何不清楚的解释,我会编辑a.s.a.p
解决方法
将“->withTimestamps()”添加到您的关系中以添加它们。
public function comments() {
return $this->hasMany(Comment::class)->withTimestamps();
}
在要更改格式的每个模型中,添加以下内容:
protected $casts = [
'created_at' => 'datetime:{format}',];
用您想要的格式替换 {format}。我认为是“c”之类的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。