【问题标题】:Join three tables in Scala Slick or flatten nested tuples在 Scala Slick 中加入三个表或展平嵌套元组
【发布时间】:2020-09-06 18:23:59
【问题描述】:

由于第一个表中的外键,我需要对三个表进行 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)。 那么我应该如何加入这些表以获得扁平元组,或者如果不能这样做,我该如何扁平化这个元组?

编辑:

实际上,我发现的唯一对我有用的解决方案是手动使用地图:

  def list(): Future[Seq[(Product, Category, 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)))
  }

看起来和感觉都很糟糕。但到目前为止只有这个有效...... 有更好的想法吗?

【问题讨论】:

  • 这能回答你的问题吗? multiple joins with slick
  • @AlleXyS:你提供的答案给出了我现在得到的嵌套元组的结果

标签: scala tuples slick


【解决方案1】:

内连接在 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, Category, Supplier)]] = db.run {
  for {
    product <- productTable
    category <- product.category
    supplier <- product.supplier
  } yield (product, category, supplier)
}

【讨论】:

    猜你喜欢
    • 2014-05-28
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2017-10-10
    • 2020-10-04
    • 2018-10-28
    • 1970-01-01
    相关资源
    最近更新 更多