sql - 你能加入两个表并得到一个包含 obj 列表(来自第二个表)的 obj(来自第一个表)
问题描述
首先是我的代码:
表 1:
object Company : Table() {
val name = varchar("pk_name", 250)
override val primaryKey = PrimaryKey(name, name = "pk_company_constraint")
}
表 2&3:
object Sector : IntIdTable() {
val name = varchar("fk_name", 50).references(MainSector.name)
val alias = varchar("alias", 50).nullable()
val companyName = varchar("fk_company_name", 250).references(Company.name, onDelete = ReferenceOption.CASCADE)
}
object MainSector : Table() {
val name = varchar("pk_name", 50)
override val primaryKey = PrimaryKey(name, name = "pk_main_sector_constraint")
}
我的问题:
我需要将结果解析为如下所示的 DTO:
data class CompanyDTO (
val companyName: String,
val sectorList: List<SectorDTO>
)
data class SectorDTO (
val mainSectorName: String,
val sectorAlias: String
)
我能够从数据库中获得第一个部门的公司,但我不知道如何获取它们的列表。
我的尝试:
override fun retrieveCompanies(vararg names: String): List<CompanyDTO> {
var retlist: List<CompanyDTO> = emptyList()
if (names.isEmpty()){
retlist = transaction {
(Company innerJoin Sector)
.select{Company.name eq Sector.companyName}
.map { CompanyDTO(it[Company.name], listOf(
SectorDTO(it[Sector.name], it[Sector.alias]?: "")
)) }
}
} else {
//return specific
}
return retlist
}
如果没有给出参数,我想返回数据库中的所有公司,如果给出参数,我想只返回具有给定名称的公司。我在官方文档中找不到有关此主题的任何内容,请发送帮助
解决方案
如果Company
没有任何Sector
你需要使用leftJoin
的,那么你的代码可能是这样的:
Company.leftJoin.Sector.selectAll().map {
val companyName = it[Company.name]
val sector = it.tryGet(Sector.name)?.let { name ->
SectorDTO(name, it[Sector.alias].orEmpty())
}
companyName to sector
}.groupBy({ it.first }, { it.second }).map { (companyName, sectors) ->
CompanyDTO(companyName, sectors.filterNotNull())
}
推荐阅读
- terraform - 通过传入变量创建动态 yaml 文件
- javascript - 查找特定日期的可用时间
- deployment - 如果 Django 部署超时,如何获取 AWS Elastic Beanstalk 日志以找出问题的原因?
- javascript - 发生错误时如何防止文件系统访问 API 保存文件?
- python - 如何为 lmfit 最小二乘法选择初始值?
- python - Django ORM 操作 django ORM 查询的更好方法
- reactjs - 在句柄提交中使用异步等待
- css - 顺风背景不透明度
- r - R ggplot facet label在y轴标题和y轴刻度标签之间的位置
- python - “品脱”中派生维度中数量的标准格式