You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Vapor-Fluent中按标题排序,如何修正丹麦语特殊字符排序错误?

修复Fluent中丹麦语特殊字符排序问题

问题根源是默认字符串排序采用ASCII顺序,无法识别丹麦语å、æ、ø的专属排序规则。以下是两种可行的解决方式:

方案1:数据库层面配置丹麦语排序规则(推荐)

根据你使用的数据库类型,通过迁移文件设置对应排序规则:

PostgreSQL环境

新增迁移文件更新列的排序规则:

struct UpdateAttractionDanishCollation: AsyncMigration {
    func prepare(on database: Database) async throws {
        try await database.schema(Attraction.schema)
            .modifyField(Attraction.FieldKeys.title, .string, .required, .collation("danish"))
            .modifyField(Attraction.FieldKeys.description, .string, .collation("danish"))
            .update()
    }

    func revert(on database: Database) async throws {
        try await database.schema(Attraction.schema)
            .modifyField(Attraction.FieldKeys.title, .string, .required)
            .modifyField(Attraction.FieldKeys.description, .string)
            .update()
    }
}

在configure文件中添加该迁移:

app.migrations.add(UpdateAttractionDanishCollation())

执行迁移后,原有的sort查询会自动遵循丹麦语排序规则。

MySQL环境

修改迁移文件设置表的丹麦语排序规则:

struct UpdateAttractionDanishCollation: AsyncMigration {
    func prepare(on database: Database) async throws {
        try await database.schema(Attraction.schema)
            .modify { schema in
                guard let mysqlSchema = schema as? MySQLSchema else { return }
                mysqlSchema.collation = "utf8mb4_danish_ci"
            }
            .update()
    }

    func revert(on database: Database) async throws {
        try await database.schema(Attraction.schema)
            .modify { schema in
                guard let mysqlSchema = schema as? MySQLSchema else { return }
                mysqlSchema.collation = "utf8mb4_general_ci"
            }
            .update()
    }
}

添加迁移并执行后即可生效。

方案2:SQLite环境下的替代处理

SQLite默认不支持语言专属排序规则,可在查询后用Swift本地化排序处理:

func getAttractionsHandler(_ req: Request) async throws -> [Attraction] {
    let attractions = try await Attraction.query(on: req.db).all()
    return attractions.sorted {
        $0.title.localizedStandardCompare($1.title) == .orderedAscending
    }
}

localizedStandardCompare会自动适配系统的丹麦语排序逻辑,正确处理å、æ、ø的排序顺序。

内容的提问来源于stack exchange,提问作者Mitul Pokiya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 10:11:08