通过关联方式 follow 其他用户,创建时间和更新时间没有填充?

代码

class User  extends Authenticatable
{
    ...

    public function followers()
    {
        return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id');
    }

    public function followings()
    {
        return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id');
    }

    public function follow($user_ids)
    {
        if (!is_array($user_ids)) {
            $user_ids = compact('user_ids');
        }
        $this->followings()->sync($user_ids, false);
    }

    public function unfollow($user_ids)
    {
        if (!is_array($user_ids)) {
            $user_ids = compact('user_ids');
        }
        $this->followings()->detach($user_ids);
    }

    public function isFollowing($user_id)
    {
        return $this->followings->contains($user_id);
    }
}

file

--Max--
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

在处理 User 和 followers 或者 followings 关联的时候加上 withTimestamps 方法,比如:

public function followers()
{
    return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id')
                ->withTimestamps();
}
7年前 评论
Maxwells (楼主) 6年前
讨论数量: 2

在处理 User 和 followers 或者 followings 关联的时候加上 withTimestamps 方法,比如:

public function followers()
{
    return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id')
                ->withTimestamps();
}
7年前 评论
Maxwells (楼主) 6年前

在followings方法中加上withTimestamps方法。

public function followings()
    {
        return $this->belongsToMany(User::Class, 'followers', 'follower_id', 'user_id')->withTimestamps();
    }
7年前 评论
Maxwells (楼主) 6年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!