2014-05-05 14 views
5

Wie können Joins für mehrere Felder wie in Beispiel unten durchgeführt werden?Scala Slick 2 Join auf mehreren Feldern?

val ownerId = 1 
val contactType = 1 
... 
val contact = for { 
    (t, c) <- ContactTypes leftJoin Contacts on (_.id === _.typeId && _.ownerId === ownerId) 
    if t.id === contactType 
} yield (c.?, t) 

Wie kann ich dies mit Slick 2.0.1 erreichen? Idelly muss ich glatt diese Art der Abfrage zu erzeugen

SELECT 
    x2."contact_id", 
    x2."type_id", 
    x2."owner_id", 
    x2."value", 
    x2."created_on", 
    x2."updated_on", 
    x3."id", 
    x3."type", 
    x3."model" 
FROM 
    (
     SELECT 
      x4."id" AS "id", 
      x4."type" AS "type", 
      x4."model" AS "model" 
     FROM 
      "contact_types" x4 
    )x3 
LEFT OUTER JOIN(
    SELECT 
     x5."created_on" AS "created_on", 
     x5."value" AS "value", 
     x5."contact_id" AS "contact_id", 
     x5."updated_on" AS "updated_on", 
     x5."type_id" AS "type_id", 
     x5."owner_id" AS "owner_id" 
    FROM 
     "contacts" x5 
)x2 ON x3."id" = x2."type_id" AND x2.owner_id = 1 
WHERE 
    (x3."id" = 3) 

Bitte beachten Sie ON x3. "Id" = x2. "Type_id" UND x2.owner_id = 16

Antwort

3

Ok, also nach über Websites Graben und Quellcode ich glaube, ich fand schließlich die Lösung

leftJoin on() Methode akzeptiert folgende Parameter pred: (E1, E2) => T, so können wir einfach tun, wie diese

val contacts = for { 
    (t, c) <- ContactTypes leftJoin Contacts on ((type, contact) => { 
    type.id === contact.typeId && contact.ownerId === ownerId 
    }) 
} yield (c.?, t) 

Welche generierte SQL-Abfrage nach Bedarf.

+1

Die rechte on-Klausel ist: {case (type, contact) => type.id === contact.typeId && contact.ownerId === ownerId } Die inneren Klammern von Vlad macht keinen Sinn. – Epicurist

+0

@Epicurist warum? Könnten Sie bitte erklären? –

+0

Stimmen Sie nicht zu, dass type.id === contact.typeId && contact.ownerId === ownerId überhaupt keine Klammern benötigt? – Epicurist