Expand JoinAssociation to two TableRecord rather than requiring a CTE #1434
Replies: 2 comments 5 replies
-
Hello @dawilliams-gpsw, You can create an association even if there is no foreign key in the database, with an explicit extension Foo: TableRecord {
static let barForeignKey = ForeignKey(["value"], to: ["value"])
static let bar = belongsTo(Bar.self, using: barForeignKey)
}
// SELECT foo.*, bar.*
// LEFT JOIN bar ON bar.value = foo.value
// ...
Foo.including(optional: Foo.bar)... If you need to perform a join with a condition that is not an equality check, such as |
Beta Was this translation helpful? Give feedback.
-
To borrow from Poker parlance, I'll see your This extension allows a join from one extension QueryInterfaceRequest {
public func association<Destination>(
to queryInterfaceRequest: QueryInterfaceRequest<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
to: queryInterfaceRequest.relation,
condition: .expression { condition($0, $1).sqlExpression })
}
} Unfortunately, because it uses a module-private constructor for Personally, I use this for joining between two instances of I asked @groue if he would add this capability to GRDB. This was a long time ago, but my recollection is that he declined. :( |
Beta Was this translation helpful? Give feedback.
-
Hey y'all! I was wondering if it would be possible to expand
JoinAssociation
to work beyond just CTEs. I think it can be useful to write an on the fly join across two tables based on a common column.For example, I have a table "Foo" with two properties,
id
andvalue
. I have another table named "Bar" with a bunch of properties, but it includesvalue
as well. I would like to join these two tables over thevalue
property. I imagine that I can go to myFoo
andBar
models and add a link, via ahasOne
relationship via that foreign key, but it doesnt seem possible to use the initializer to manually create it on the fly (because it's not public), nor can I useFoo.association(to: Bar.self, on: { ... })
because it requires CTEs. Perhaps there's a way to make another CTE that is justBar.all()
as the request, but I have been having trouble getting it to work the same way as a simple join, and in that case it seems like additional noise in code.Is this restriction there for a reason, or would it be possible to open it up to all TableRecord conformers?
Beta Was this translation helpful? Give feedback.
All reactions