How can I select last record in table from database in ktor?
my data class
data class ArticleInfoDTO(
val id: Int,
val likes: Int,
val views: Int,
)
my function
object ArticlesInfo : Table("articles_info") {
private val id = ArticlesInfo.integer("id")
private val likes = ArticlesInfo.integer("likes")
private val views = ArticlesInfo.integer("views")
fun fetchArticleInfoLastRecord(): ArticleInfoDTO {
return transaction {
ArticlesInfo.select { } // what should I write in curly braces?
}
}
CodePudding user response:
data class ArticleInfoDTO(
val id: Int,
val likes: Int,
val views: Int,
)
object ArticlesInfo : Table("articles_info") {
private val id = ArticlesInfo.integer("id")
private val likes = ArticlesInfo.integer("likes")
private val views = ArticlesInfo.integer("views")
fun fetchArticleInfoLastRecord(): ArticleInfoDTO? = transaction {
ArticlesInfo.selectAll().lastOrNull()?.toArticleInfo()
}
private fun ResultRow.toArticleInfo() = ArticleInfoDTO(
this[id],
this[likes],
this[views]
)
}
CodePudding user response:
I would advise something like:
val lastInfo = ArticlesInfo.selectAll().orderBy(ArticlesInfo.id, SortOrder.DESC).limit(1).singleOrNull()?.toArticleInfo()