【问题标题】:Mapping OneToMany in Scala Play framework not inserting data to the second table在 Scala Play 框架中映射 OneToMany 不向第二个表插入数据
【发布时间】:2015-09-11 08:17:03
【问题描述】:

问题是 - 我应该如何从这种输入中获取数据并将其正确传递给 DB(通过 SORM 框架)?

我尝试将数据传递到我的数据库中的两个表,我的工作结果是,虽然值已正确插入到第一个表(作者),但第二个表(书)保持不变。 可能我的问题是我没有正确命名页面上的嵌套重复输入,但我找不到正确的方法来做到这一点(我对 Scala 还很陌生,所以我可能缺乏这方面的经验)。

Ok(Json.toJson(author)) 

在 Application.scala 中的 addData 中向我展示了

{"name":"what","books":[]}

所以我认为,问题在于从请求中绑定数据。

我尝试在此处遵循示例:How to model an entity with many children in Sorm? 和此处:https://www.playframework.com/documentation/2.1.1/ScalaForms,通过对 Play 框架中的模板“play-scala”进行操作,所以我有这样的代码:

型号是:

case class Author(name: String, books: Seq[Book]) {
}
object Author {
implicit val authorFormat = Json.format[Author]
}

case class Book(title: String ) {
}
object Book {
implicit val bookFormat = Json.format[Book]
}

case class AuthorBook(name: Author, title: Book) {
}

scala.index.html

<table>
    <tr>
        <td>
        On the left Author, on the right Book
        <td>
    </tr>
    <tr>
    <td>
        <ul id="authors"></ul>
    </td>
    <td>
        <ul id="books"></ul>
    </td>
    </tr>
</table>

<table>
    <form action="@routes.Application.addData()" method ="post">
        <tr>
            <td>Author: <input name="author" type="text">
        </td>       
            <td>Books: <input name="books.title[0]" type="text"><br><input name="books.title[1]" type="text">
        </td>
        </tr>
        <tr>
            <td> 
                <button>Submit</button>
            </td>
        </tr>
    </form>
</table>

和 Application.scala

class Application extends Controller {
def index = Action {
Ok(views.html.index("E-Library"))
}

  val authorForm: Form[Author] = Form {
    mapping(
      "author" -> text,
      "books" -> seq(
          mapping(
          "title" -> text)(Book.apply)(Book.unapply)
      )
   )(Author.apply)(Author.unapply)
   }

  def error = Action {
    Ok("error")
  }

  def addData = Action { implicit request =>
      authorForm.bindFromRequest.fold(
    formWithErrors => {
      BadRequest("Bad request!")
    },
    authorF => {
      val author = DB.save(authorF)
      Ok(Json.toJson(author))
      //Redirect(routes.Application.index())
    }
  )
  }

  def getAuthor = Action {
    val dataAuthor = DB.query[Author].fetch
    Ok(Json.toJson(dataAuthor))
  }

  def getBook = Action {
    val dataBook = DB.query[Book].fetch
    Ok(Json.toJson(dataBook))
 }

  def getData = Action {
    Redirect(routes.Application.index())
  }
}

【问题讨论】:

    标签: scala playframework one-to-many psql sorm


    【解决方案1】:

    找到了! 如此处所述:Nested form in Play! Scala 2.2

    我需要将表单中的输入名称从 book.title[0]book[0].title.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多