首页 > 解决方案 > 你能加入两个表并得到一个包含 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
    }

如果没有给出参数,我想返回数据库中的所有公司,如果给出参数,我想只返回具有给定名称的公司。我在官方文档中找不到有关此主题的任何内容,请发送帮助

标签: sqlkotlinkotlin-exposed

解决方案


如果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())
}

推荐阅读