微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Laravel 中将时间戳转换为 unix 时间戳?

如何解决如何在 Laravel 中将时间戳转换为 unix 时间戳?

SO 伟大的人们你好

希望你们都有美好的一天!

我的项目时间戳有问题

我有 2 个模型,NewsComments

在我的项目工作期间,我试图复制“真实世界的数据”

所以在我的 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?