Skip to content

Constant ForeignKey value #1733

Answered by groue
seanmrich asked this question in Q&A
Feb 25, 2025 · 1 comments · 3 replies
Discussion options

You must be logged in to vote

Hello @seanmrich,

Your solution is to define an association based the id column, and filtered on the table column:

extension Player {
    static let mapping = hasOne(Mapping.self, using: ForeignKey(["id"]))
        .filter(Column("table") == databaseTableName)
}

Note that I've used hasOne because each player has zero or one matching row in the mapping table, thanks to the primary key.

I can reproduce your target SQL query:

// SELECT COUNT(*) FROM (
//     SELECT "players"."id"
//     FROM "players"
//     LEFT JOIN "mapping" ON ("mapping"."id" = "players"."id") AND ("mapping"."table" = 'players')
//     WHERE ("players"."deleteDate" IS NULL) AND ("mapping"."rowid" IS NOT NULL)
// )
let ma…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@groue
Comment options

@seanmrich
Comment options

@groue
Comment options

Answer selected by seanmrich
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants