在开发时遇到一个坑,用户与粉丝之间的互动,是使用的 laravel
的多对多方法 sync()
,但是这个方法有个问题,就是在相互关注时,无法自动添加时间戳。所以需要在关联关系中使用withTimestamps()
,才能解决此问题:
/**
* 用户拥有的粉丝
*/
public function followers(): BelongsToMany
{
return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id')
->orderByDesc('created_at')->withTimestamps();
}
// 用户支持过的用户
public function followings(): BelongsToMany
{
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id')
->orderByDesc('created_at')->withTimestamps();
}
这样在使用sync()
方法时才会自动为字段添加上时间戳。