首页 文章

保存相关模型时,Laravel 5.2.x从模型更改update_at字段?

提问于
浏览
2

想象一下,您有一个与许多角色相关的模型用户,其中角色也由其他用户共享 .

用户模型在数据库上还有一个updated_at字段,当用户的任何字段更新时,该字段将更新为当前时间 . 如果用户名更改,则其updated_at字段也会更改 .

如果您只是更改用户相关角色会发生什么? Should you update the updated_at field or not?

如果是这样,在更新用户的相关角色时,有什么方法可以自动更新此字段?

我的解决方案:

public function update(Request $request, $id) 
{
    ...

    $user->update($data);
    $roles = $user->roles()->sync($request->get('roles'));

    if (!empty($roles['attached']) || 
        !empty($roles['detached'])) { // <!-- Is there a better way to check these conditions?

        $user->touch();
    }
}

2 回答

  • 2

    你可以做的是在 Role 模型中添加以下属性:

    protected $touches = ['user'];
    

    您还需要具有以下关系:

    public function user() 
    {
       return $this->belongsToMany(User::class);
    }
    

    这样,每次为这些用户更新 updated_at 字段时,为用户附加或分离角色时 .

    请注意,当您仅更新角色模型时也会使用此选项 - 如果您更新角色模型,则会自动为已分配此角色的用户更新 updated_at 列 .

    EDIT

    对不起,我错过了你问你是否应该这样做的部分 . 在我看来 - 而不是 . 在 updated_at 中,您应该在更新直接对象时保持 . 我可以理解它,例如你有用户模型,每个用户你也有 Profiles 模型 . 在这种情况下,更新配置文件模型可能会导致更新用户模型的时间戳,但在这种情况下我不会使用它 . 如果需要,您可以在数据透视表中使用时间戳字段,如果您需要保留一些更改历史记录,我宁愿为此创建专用解决方案,以便用User保存相关模型的更改日期,而不是每次相关时更新 updated_at 将被附加/分离/更新 . 但当然一切都取决于应用需求 . 可能在某些情况下这可能是一个很好的解决方案,但目前我无法想到 .

    参考:Touching parent timestamps

  • 1

    您没有技术原因 should (或不应该)更新相关的 updated_at 时间戳 . 它完全取决于对您的应用程序最有意义的东西 .

    Updating related timestamps automatically

    Laravel支持模型上的 $touches 属性(docs):

    class Role extends Model
    {
        /**
         * All of the relationships to be touched.
         *
         * @var array
         */
        protected $touches = ['users'];
    
        /**
         * Get the users that have this role.
         */
        public function users()
        {
            return $this->belongsToMany('App\User');
        }
    }
    

    Updating timestamps manually

    如果您只想将 updated_at 设置为当前时间,请按照问题中的建议使用 $user->touch() 方法 .

相关问题