multiple joins with slick
Asked Answered
R

2

20

For joining between two tables is done like

    (for {
    (computer, company) <- Computers leftJoin Companies on (_.companyId === _.id)
    if computer.name.toLowerCase like filter.toLowerCase()
    }

But in case if joining required between more tables what is the right way trying below but doesnt work

   (for {
    (computer, company,suppliers) <- Computers leftJoin Companies on (_.companyId ===        _.id)
     //not right leftjoin Suppliers on (_.suppId === _.id)
    if computer.name.toLowerCase like filter.toLowerCase()
  }
Revolutionist answered 30/8, 2013 at 16:52 Comment(1)
computer is associated with supplierRevolutionist
H
36

The first join results in a Query returning Tuples. One of the tuple components has the foreign key you want to use for the second join. You need to get this component in the second join condition before getting its field. If Companies is the table, that has the field suppId it would look like this:

(for {
  ((computer, company),suppliers) <- Computers leftJoin Companies on (_.companyId === _.id) leftJoin Suppliers on (_._2.suppId === _.id)
  if computer.name.toLowerCase like filter.toLowerCase()
} yield ... )
Hotchpot answered 31/8, 2013 at 12:37 Comment(3)
here leftJoin Suppliers on (._2.suppId === _.id) is this join on the first tuple? in case if want to join between computer and suppliers i am trying with leftJoin Suppliers on (._1.suppId === _.id) but this one failsRevolutionist
This works, but i see that the full query with joins should be in one line , else its showing compilation errorsRevolutionist
changed the answer to be in one lineHotchpot
C
4

I think you want this:

for {
    (computer, company) <- Computers leftJoin Companies on (_.companyId === _.id)
    (supp, _) <- company innerJoin Suppliers on (_.suppId === _.id)
    if computer.name.toLowerCase like filter.toLowerCase()
} yield (computer, company, supp)

Of course, I am making assumptions about your model. Not sure if suppliers are linked with companies or computers.

Chabot answered 1/9, 2013 at 7:16 Comment(5)
I like that the second join is a separate line in the "for" comprehension.Marilumarilyn
how does company do the inner join here ? It a model type? (second line in for loop)Dyne
company is the one defined in the previous line.Chabot
Because you can't reuse company as a Query, it is a Projection. I tested this solution 3 times on Slick 2.1 :pBirchard
Look at the date of question and date of the answer. Anyways, if I get time I will amend the question.Chabot

© 2022 - 2024 — McMap. All rights reserved.