代码之家  ›  专栏  ›  技术社区  ›  Yola

如何检测数据库中是否存在具有相同字段值的对象

  •  0
  • Yola  · 技术社区  · 2 年前

    我有以下型号

    @Model
    final class Location {
        @Attribute(.unique) var name: String
        
        init(name: String) {
            self.name = name;
        }
    }
    

    我有这个项目的EditView。我不想让人们尝试使用现有名称保存项目。

            Button("Save") {
                withAnimation {
                    save()
                    dismiss()
                }
            }
            // Require a name to save changes.
            .disabled(
                name == "" || !isUnique())
    

    ...

    private func isUnique() -> Bool {
        ForEach(locations) { location in
            if location.name == name {
                return true;
            }
        }
        return false;
    }
    

    我在中遇到了一些设计时错误 isUnique 作用如何正确地做到这一点?

    1 回复  |  直到 2 年前
        1
  •  1
  •   Joakim Danielson    2 年前

    如果不能在内存中进行检查,则应执行单独的提取

    func locationExists(for name: String, in modelContext: ModelContext) throws -> Bool {
        let predicate = #Predicate<Location> { $0.name == name }
        let fetchDescriptor = FetchDescriptor<Location>(predicate: predicate)
    
        return try modelContext.fetchCount(fetchDescriptor) > 0
    }
    

    我不知道为什么你的函数不起作用,但我会把它写成

    private func isUnique(for name: String) -> Bool {
        locations.contains(where { $0.name == name }) == false
    }