gpt4 book ai didi

php - 带有数据透视表的人类可读时间戳 Laravel 4

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:02:47 25 4
gpt4 key购买 nike

如果在数据透视表中使用,是否有办法以人类可读的格式显示 created_at 和 updated_at 时间戳?

我对整个 laravel 数据透视表一无所知,但现在我正在使用数据透视表来存储用户对各个帖子的评论,并且每个帖子都有 created_at 和 updated_at 时间戳。

如果我只是使用带有模型的普通表,我会扩展我的基本模型,如下所示:

use Carbon\Carbon;

class Base extends Eloquent {

protected function getHumanTimestampAttribute($column)
{
if ($this->attributes[$column])
{
return Carbon::parse($this->attributes[$column])->diffForHumans();
}

return null;
}

public function getHumanCreatedAtAttribute()
{
return $this->getHumanTimestampAttribute("created_at");
}

public function getHumanUpdatedAtAttribute()
{
return $this->getHumanTimestampAttribute("updated_at");
}

}

但由于我没有为数据透视表使用模型,我该如何解决这个问题?有没有办法让这些功能与我的数据透视表一起使用?将模型用于数据透视表是否是最简单/正确的方法?

编辑这就是我的关系在我的用户模型中的样子。

/**
* Guide comments
*
* @return mixed
*/

public function guide_comments()
{
return $this->belongsToMany('Guide', 'guides_comment')->withTimestamps();
}

最佳答案

假设我们有 2 个模型:UserCategory 具有多对多关系,因此有 pivot(category_user: id, user_id, category_id, created_at, updated_at) 表链接 2.

现在,让我们像这样建立关系:

// User model
public function categories()
{
return $this->belongsToMany('Category')->withTimestamps();
}

// Category model
public function users()
{
return $this->belongsToMany('User')->withTimestamps();
}

然后,由于默认情况下时间戳会变异为 Carbon 对象,您需要做的就是:

$user = User::with('categories');

$user->categories->first()->pivot->created_at->diffForHumans();

您不需要自定义 PivotModel,也不需要那些额外的访问器(这些访问器非常令人困惑并且一开始就完全多余)。


如果你想简化一点,实际上你可以这样定义访问器:

// same for both models
public function getPivotHumansCreatedAtAttribute()
{
if (is_null($this->pivot)) return null;

return $this->pivot->created_at->diffForHumans();
}

// then you access it like this:
Category::first()->pivotHumansCreatedAt; // null, since it's not called as relation
User::first()->categories()->first()->pivotHumansCreatedAt; // '2 days ago'

关于php - 带有数据透视表的人类可读时间戳 Laravel 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23620279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com