-
|
Hi All, I have this schema and this is the query I'm trying to use: If I do the same query without the group by clause, in the select I have 2 arguments correctly resolved, and I can create the ExpenseModel. Thanks in advance |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 13 replies
-
|
Hi @rcasula, this is quite a complex query to be performing and so it takes some work to get things in the right shape. The trick is to use a common table expression to first select all the data for the First some fixes to your data types to be identifiable and codable: @Table
struct Currency: Codable, Identifiable {
let code: String
let name: String
let symbol: String
var id: String { code }
}
@Table
struct Expense: Codable, Identifiable {
let id: UUID
let name: String
let amount: Int
let currencyCode: Currency.ID
let date: Date
}
// I want to achieve this end result:
@Selection
struct ExpenseModel: Codable {
let id: Expense.ID
let name: String
let amount: Int
let currency: Currency
let date: Date
}
@Selection
struct GroupedExpenses {
let date: Date
@Column(as: [ExpenseModel].JSONRepresentation.self)
let expenses: [ExpenseModel]
}I also dropped the But with those data types defined you can now define your query using a func fetch() {
With {
Expense
.order { $0.date.desc(nulls: .last) }
.join(Currency.all) { $0.currencyCode.eq($1.code) }
.select {
ExpenseModel.Columns(
id: $0.id,
name: $0.name,
amount: $0.amount,
currency: $1,
date: $0.date
)
}
} query: {
ExpenseModel
.group(by: \.date)
.select {
GroupedExpenses.Columns(
date: $0.date,
expenses: $0.jsonGroupArray()
)
}
}
}You can think of the query inside the |
Beta Was this translation helpful? Give feedback.
-
|
That's exactly what I needed, I was totally ignoring the common table expression part! Thank you so much! And also, thanks for pointing out the Decimal discussion! EDIT: After testing a little bit, I got an error while decoding the json for the grouped expenses:
This is the generated SQL: |
Beta Was this translation helpful? Give feedback.
Hi @rcasula, this is quite a complex query to be performing and so it takes some work to get things in the right shape. The trick is to use a common table expression to first select all the data for the
ExpenseModel, and then you aggregate that selection into aGroupedExpensesusingjsonGroupArray.First some fixes to your data types to be identifiable and codable: