In one-to-many, how to express “where is” in a spot?
Suppose two tables:
- cats,
Cat
- personality traits,
Personality_Trait
were Cat
has id
, and Personality_Trait
has a id
string trait
.
eg.
== Cat ==
id | name
---------------
0 | Tom
1 | Garfield
2 | Kitty
== Personality_Trait ===
id | trait
---------------
0 | stubborn
1 | stubborn
1 | sleepy
1 | moody
2 | sleepy
2 | moody
How do I get all cats that have at least all the traits that interest me?
eg. how do i get Garfield
when i search stubborn
andmoody
I was thinking something like
Personality_Trait.groupBy(_.id).filter {
case (id, traits) => <predicate on traits>
}.map(_._1)
+3
source to share
2 answers
I found a solution, albeit inelegant and potentially ineffective:
val desiredTraits = Set("stubborn", "moody")
(for {
catId <- Personality_Trait.filter(_.trait inSetBind desiredTraits)
.groupBy(_.id).map { case (txnId, foundTraits) =>
(txnId, foundTraits.length)
}.filter { case (txnId, foundTraitCount) =>
foundTraitCount >= desiredTraits.size
}.map(_._1)
cat <- Cat if cat.id === catId
} yield (cat)).result
0
source to share