【问题标题】:Laravel 5.1 What's the difference of lockForUpdate in DB builder and Eloquent?Laravel 5.1 DB builder和Eloquent中的lockForUpdate有什么区别?
【发布时间】:2017-03-31 22:41:59
【问题描述】:

在 Eloquent 上使用 lockForUpdate 似乎并不总是有效。

       DB::beginTransaction();
       User::find(1)->lockForUpdate();
       ... (doing some logic)
       DB::commit();

但是使用

DB::table('users')->where('id', '=', $userId)->lockForUpdate()

总是有效。这两个 lockForUpdate() 有什么区别?

  • Laravel 版本:5.1
  • PHP 版本:5.7
  • 数据库驱动和版本:MySQL 14.14

【问题讨论】:

  • 看起来很有趣的问题。但是,有效无效究竟是什么意思?请解释预期/意外的行为和错误消息(如果有)。
  • @alariva,就我而言,我尝试在每个用户的用户配置文件表中创建一个唯一条目。如果用户不小心点击了两次“保存”按钮(它并没有阻止用户触发多次点击),它将在用户配置文件表中创建两行 User::find(1)->lockForUpdate();。所以我认为它没有正确锁定。这有意义吗?
  • 现在我明白了,但这与锁定行无关,确切地说。另一方面,仅处理 users 表并不能使您免于其他表上的相同问题。我自己有the exact same problem (still unsolved) in my project. 好消息是,您至少可以为users 表做点什么。
  • 因此,您可以在迁移文件中将unique() 设置为users 表的emailusername 字段。这里an example

标签: php mysql laravel-5


【解决方案1】:
User::lockForUpdate()->find(1);

这样就可以了

find() 将返回模型而不是查询生成器。

lockForUpdate() 是来自查询生成器的方法

【讨论】:

    猜你喜欢
    • 2015-12-03
    • 2013-04-14
    • 1970-01-01
    • 2017-10-01
    • 2011-04-11
    • 2017-01-03
    • 2016-10-17
    • 2015-12-18
    • 2015-02-22
    相关资源
    最近更新 更多