我在迭代传递给 Play 框架模板的列表时遇到问题。我基本上有一个从多对多关联中获取的查询,我想渲染一次父键和多次关联键。
以下是我正在使用的实际代码:
使用 Slick、Scala 和 Play 2.0,我有以下表模式:
object Recipes extends Table[(Long, String, String)]("RECIPES") {
def id = column[Long]("REC_ID", O.PrimaryKey, O.AutoInc)
def cuisine = column[String]("CUISINE")
def instructions = column[String]("INSTRUCTIONS")
def * = id ~ cuisine ~ instructions
}
object Ingredients extends Table[(Long, String, String)]("INGREDIENTS") {
def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
def brand = column[String]("BRAND")
def name = column[String]("NAME")
def * = id ~ brand ~ name
}
object RecipeIngredient extends Table[(Long, Long, Long, Int, String)]("REC_ING") {
def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
def recID = column[Long]("REC_ID")
def ingID = column[Long]("ING_ID")
def quantity = column[Int]("QUANTITY")
def units = column[String]("UNITS")
def * = id ~ recID ~ ingID ~ quantity ~ units
def recipe = foreignKey("REC_FK", recID, Recipes)(_.id)
def ingredient = foreignKey("ING_FK", ingID, Ingredients)(_.id)
}
我正在使用 Slick 在控制器中生成以下查询,并传递q.list
给视图。这个想法是传递和渲染 ID 为 1 的配方及其所有相关成分:
val recID = 1.longValue() // Just a test to get the Recipe with ID === 1
val q = for {
r <- Recipes if r.id === recID
ri <- RecipeIngredient if ri.recID === recID
i <-Ingredients if i.id === ri.ingID
} yield (r.id, r.cuisine, r.instructions, ri.quantity, ri.units, i.brand, i.name)
我的看法如下:
@(message: String, result: List[(Long, String, String, Int, String, String, String)])
@main("Site name") {
@for((id, cuisine,instructions, quantity, units, brand, name) <- result) {
<h2>--Recipe--</h2>
RecID: @id <br>
Cuisine: @cuisine <br>
Instructions: @instructions <br>
<h2>--Ingredients--</h2>
Ingredient: @quantity @units of @brand @name<br>
}
}
这一切都很好,但我得到如下输出:
--Recipe--
RecID: 1
Cuisine: Chinese
Instructions: Instructions here..
--Ingredients--
Ingredient: 3 cloves of Generic Ginger
--Recipe--
RecID: 1
Cuisine: Chinese
Instructions: Instructions here..
--Ingredients--
Ingredient: 3 slices of Generic Cucumber
如您所见,配方本身重复了两次。我最终想要的是打印一次的食谱,以及在此之后交互和显示的相关成分列表(可能有多种成分)。
关于如何实现这一目标的任何想法?