【问题标题】:How can I update a field of relational table with a data from a related table如何使用相关表中的数据更新关系表的字段
【发布时间】:2019-04-30 09:10:54
【问题描述】:

我需要更新关系表的值。 我在关系表中有book_idauthor_id,我从Book 表中获得Idvalue 和Author 表的Id 值,我想从book_id 更改author_id

我使用 Grails 进行了此操作,但没有成功。 我正在使用包含 Hibernate 和 Spring 的 Grails 框架。

        Book bookToEdit = Book.findById(bookId)
        Author newAuthor = Author.findById(authorId)
        BookAuthor bookAuthor = BookAuthor.findByBook(bookToEdit)
        bookAuthor.author = newAuthor
        bookAuthor.save(flush:true)

当我调试此代码并提交我的更改时,我收到了作者的原始 ID,而不是提交的更改。

【问题讨论】:

    标签: java grails


    【解决方案1】:

    您不应该自己编辑关系表。如果你有一个 Book 类,比如:

    class Book {
       String title
       Author author
    }
    

    那么你应该可以做到这一点,并且关系表会适当更新:

    Book bookToEdit = Book.findById(bookId)
    Author newAuthor = Author.findById(authorId)
    book.author = newAuthor
    book.save(flush:true)
    

    【讨论】:

    • 谢谢!只是当我没有输入所有必要的值时,我试图更新表格。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 2020-03-10
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    相关资源
    最近更新 更多