代码之家  ›  专栏  ›  技术社区  ›  Jocky Doe

Model::create是否创建数据库事务

  •  0
  • Jocky Doe  · 技术社区  · 8 年前

    我想出了这样的一对一插入代码:

    $anotherPet = \App\Pet::create($data);
    $anotherUser = \App\User::create($data);
    $anotherPet->user()->associate($anotherUser);
    
    $anotherPet->save();
    

    create() 调用db,或者在 save() ?

    3对1通话?

    感谢你的帮助。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Yannis Berrouag    8 年前

    假设您使用的是laravel,则创建一个事务,如果您只需要一个,您可以创建一个新实例并填充它,如下所示:

    $anotherPet = new \App\Pet;
    $anotherPet->fill($data);
    $anotherUser = \App\User::create($data); // transaction is made here; mandatory to have an id for your association
    
    $anotherPet->user()->associate($anotherUser); // no transaction
    $anotherPet->save(); // transaction is made here
    

    这样,您将有2个查询,而不是3个查询,我没有办法在一个查询中使用外键约束失败。