jac*_*dev 4 php laravel eloquent
有没有办法以人类可读的格式显示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");
}
}
Run Code Online (Sandbox Code Playgroud)
但是,由于我不使用数据透视表的模型,我将如何解决这个问题?有没有办法让这些功能与我的数据透视表一起使用?使用数据透视表的模型是最简单/正确的方法吗?
编辑 这就是我的关系看起来像是放在我的用户模型中.
/**
* Guide comments
*
* @return mixed
*/
public function guide_comments()
{
return $this->belongsToMany('Guide', 'guides_comment')->withTimestamps();
}
Run Code Online (Sandbox Code Playgroud)
想象一下,我们有2个模型:User
并且Category
具有多对多关系,因此使用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();
}
Run Code Online (Sandbox Code Playgroud)
然后,由于Carbon
默认情况下时间戳会变为对象,所以您需要做的就是:
$user = User::with('categories');
$user->categories->first()->pivot->created_at->diffForHumans();
Run Code Online (Sandbox Code Playgroud)
您不需要自定义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'
Run Code Online (Sandbox Code Playgroud)