Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using a Joined Table column as the first column in the .order() function #1630

Closed
martindufort opened this issue Sep 18, 2024 · 1 comment
Closed
Labels

Comments

@martindufort
Copy link

Hey Groue, ca va?

It's been a while and I thinking I'm losing my GRDB IQ.

So here goes:

Using Joined Table Column in order clause

I have a table A with a hasMany relationship to table B.
I want to perform a query where the column name in the joined table B is the first item in the order statement.

I've tried this:

try TableA
   .joining(required: TableA.tableBAssociation
		.filter(TableB.Columns.count > 0)
		.order(TableB.Columns.name.desc)
		)
   .group(TableA.Columns.uuid)
   .order(TableA.Columns.subject)
   .fetchAll(db)

This puts the TableB.name column as the last item in the order by clause.

Then I read the documentation and tried asking you know who.
Finally I was able to resolve this by declaring the TableB column explicitly

Here's the sample code

let firstItem = SQL(“tableB.name”).sqlExpression
try TableA
   .joining(required: TableA.tableBAssociation
		.filter(TableB.Columns.count > 0)
		)
   .group(TableA.Columns.uuid)
   .order(firstItem.desc, TableA.Columns.subject)
   .fetchAll(db)

Question?

Is this the best way? I would rather not specify the column name of TableB using this string construction.
Let me know what I have missed.

Thanks

@martindufort martindufort changed the title Using a Joined Table column has the first column in the .order() function Using a Joined Table column as the first column in the .order() function Sep 18, 2024
@groue
Copy link
Owner

groue commented Oct 12, 2024

Hello @martindufort,

Sorry for the late response, I clearly missed a notification.

Your code works, so that's good 👍

The "official" way to implement this is a TableAlias:

let bAlias = TableAlias()
try TableA
   .joining(required: TableA.tableBAssociation
                            .aliased(bAlias)
		            .filter(TableB.Columns.count > 0))
   .group(TableA.Columns.uuid)
   .order(bAlias[TableB.Columns.name].desc, TableA.Columns.subject)
   .fetchAll(db)

@groue groue closed this as completed Oct 12, 2024
@groue groue added the support label Oct 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants