在开发时遇到一个坑,用户与粉丝之间的互动,是使用的 laravel 的多对多方法 sync(),但是这个方法有个问题,就是在相互关注时,无法自动添加时间戳。所以需要在关联关系中使用withTimestamps(),才能解决此问题:

    1. /**
    2. * 用户拥有的粉丝
    3. */
    4. public function followers(): BelongsToMany
    5. {
    6. return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id')
    7. ->orderByDesc('created_at')->withTimestamps();
    8. }
    9. // 用户支持过的用户
    10. public function followings(): BelongsToMany
    11. {
    12. return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id')
    13. ->orderByDesc('created_at')->withTimestamps();
    14. }

    这样在使用sync()方法时才会自动为字段添加上时间戳。