Slick- use foreignKey constraint and access referenced object directly as column

后端 未结 1 1064
情歌与酒
情歌与酒 2021-01-05 05:04

I have two models (say, Supplier and Coffee) and Coffee model has foreign key reference to Supplier model. During ddl, I want this relation

相关标签:
1条回答
  • 2021-01-05 05:20

    In Slick you don't map to case classes that reference other case classes. To resolve foreign keys you use queries instead, which you can put into methods for re-usability.

    Also see my post at: https://groups.google.com/d/msg/scalaquery/esFb2DjoHVE/NtMj7BmpE94J

    EDIT: You can't follow a reference in coffeeObj and that is a good thing. Because that would require configuring a loading strategy like in ORMs, which would be more complicated and would make the execution behavior of your code less obvious.

    Lazy loading would probably load the coffeeObj in the controller and the supplier in the view, which seems odd, right? You can do this:

    Remove .firstOption.get from your findOneById method and then:

    val supplierQuery = Query(Suppliers).findById(id)
    val coffeeQuery = supplierQuery.join(Coffee).on(...).map(_._2)
    // here is what you want, a supplier and the corresponding coffee:
    val supplierWithCoffee = (supplierQuery.firstOption,coffeeQuery.f​irstOption)
    

    Put the join into a function to save boiler plate.

    0 讨论(0)
提交回复
热议问题