如何解决在Scala Slick中联接三个表或展平嵌套的元组
由于第一个表中的外键,我需要执行INNER JOIN三个表,如下所示:
CREATE TABLE "product" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"name" VARCHAR NOT NULL,"price" FLOAT NOT NULL,"categoryid" INT NOT NULL,"supplierid" INT NOT NULL,FOREIGN KEY(categoryid) references category(id),FOREIGN KEY(supplierid) references supplier(id)
);
在模型中,我有处理所有列表的方法:
def list(): Future[Seq[(Product,Category,Supplier)]] = db.run {
productTable.join(categoryTable).on(_.categoryid === _.id).join(supplierTable).on(_._1.supplierid === _.id).result
}
但这将返回嵌套元组而不是平面元组:(((Product,Category),Supplier)。 那么我应该如何联接这些表来获取扁平化的元组,或者,如果不可能的话,如何扁平化该元组?
编辑:
实际上,我发现对我有用的唯一解决方案是手动使用map:
def list(): Future[Seq[(Product,Supplier)]] = db.run {
productTable.join(categoryTable).on(_.categoryid === _.id).join(supplierTable).on(_._1.supplierid === _.id).result.map(a => Seq((a(1)._1._1,a(1)._1._2,a(1)._2)))
}
哪个看起来和感觉都很恐怖。但是到目前为止,只有这种方法有效... 还有更好的主意吗?
解决方法
内部连接表示为Slick中的理解力:
def list(): Future[Seq[(Product,Category,Supplier)]] = db.run {
for {
product <- productTable
category <- categoryTable if product.categoryid === category.id
supplier <- supplierTable if product.supplierid === supplier.id
} yield (product,category,supplier)
}
我还建议您查看Slick对外键查询的支持。这会使查询简单得多,它可能看起来像这样:
def list(): Future[Seq[(Product,Supplier)]] = db.run {
for {
product <- productTable
category <- product.category
supplier <- product.supplier
} yield (product,supplier)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。