【问题标题】:Vapor 3 Fluent MySQL: save on model adds 10 to auto_incrementVapor 3 Fluent MySQL:保存模型将 10 添加到 auto_increment
【发布时间】:2019-03-05 08:22:26
【问题描述】:

当我将我的对象保存到数据库时,它会将对象的 id 存储为 +10。默认情况下,表的自动增量以 1 递增。当我手动向数据库添加内容时,它会以 1 递增。

我是否缺少(或我的错误,设置)FluentMySQL 的设置?

  func storeOrUpdateItemRecord(_ item: FetcherItem, store: Store, on conn: DatabaseConnectable) throws -> EventLoopFuture<Item> {
    guard let storeId = store.id else {
      throw Abort(.internalServerError)
    }

    let calendar = Calendar.current
    let fromDate = calendar.startOfDay(for: Date())
    guard let endDate = calendar.date(bySettingHour: 23, minute: 59, second: 59, of: Date()) else { throw Abort(.internalServerError) }

    return Item.query(on: conn)
      // Bunch of filters
      .filter(\.scheduledDate < endDate)
      .all()
      .flatMap(to: Flight.self) { flights in
        if var firstItem = flights.first {
          debugPrint("Found item, updating...")
          // Update a bunch of values
          return firstItem.save(on: conn)
        }

        debugPrint("Did not find item, saving new...")
        return item.toItem(forStore: store).save(on: conn)
    }
  }

toItem 函数除了启动一个新的Item 之外什么都不做:

extension FetcherItem {

  func toItem(forStore store: Store) -> Item {
    return Item.init(
      id: nil,
      // Set a bunch of values
      actualDate: actualDateTime)
  }
}

如您所见,id 设置为 nil... 我猜应该在进行插入查询时使用 null 存储它。

数据库中的结果:

我错过了什么?

更新: 在遵循this page 的建议后,我为查询添加了日志记录......它们似乎可以正常工作。 fluent 查询的示例:

[mysql] [2019-03-06 08:49:44 +0000] INSERT INTO `Items` (`company`, `name`, `storeId`, [...] `scheduledDate`) VALUES (?, ?, ?, ?, ?, ?, ?, ?) [string("A company"), string("abc123"), integer8(1), [...] time(2019-3-6 16:25:0.0)]

如您所见,它不会以任何方式设置id。也许是 MySQL 的问题?

【问题讨论】:

    标签: mysql swift vapor vapor-fluent


    【解决方案1】:

    发现问题。 MySQL 已将@@auto_increment_increment 设置为10,因此发生了跳跃。

    更多信息在这里:

    如果您遇到此问题,请运行以下命令 (source):

    • SELECT @@auto_increment_increment

    并设置它:

    • SET @@auto_increment_increment=1

    【讨论】:

      猜你喜欢
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      相关资源
      最近更新 更多