0

First of all my code:
Table 1:

object Company : Table() {
    val name = varchar("pk_name", 250)
    override val primaryKey = PrimaryKey(name, name = "pk_company_constraint")
}

Table 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")
}

My Problem:
I need to parse the result into a DTO that looks like this:

data class CompanyDTO (
        val companyName: String,
        val sectorList: List<SectorDTO>
)
data class SectorDTO (
        val mainSectorName: String,
        val sectorAlias: String
)

I am able to get a Company with the first Sector from the database, but i have no idea how to get a list of them.
My try:

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
    }

If no arguments are given i want to return all companies from the database, if arguments are given i want to return only companies with given name. I can“t find anything about this topic in the official documentation, please send help

Felix
  • 1

1 Answers1

0

If Company could not have any Sector you need to use leftJoin and then your code could be like:

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())
}
Tapac
  • 1,889
  • 1
  • 14
  • 18