How to ensure a unique constraint applies to multiple columns (mm_book_id and mm_author_id)?

I would like to know if anyone has any ideas on how to make sure the mm_author_books join mm_author_books , how to make sure that the columns ( mm_book_id and mm_author_id ) are unique? For example, I do not want the table to contain duplicate book_id and author_id , such as 1.1 and 1.1. So how to do it ...

 class Book { String title static belongsTo = Author static hasMany = [authors:Author] static mapping = { authors joinTable:[name:"mm_author_books", key:'mm_book_id' ] } } class Author { String name static hasMany = [books:Book] static mapping = { books joinTable:[name:"mm_author_books", key:'mm_author_id'] } } 

I tried this in the domain "mm_author_books":

 class mm_author_books { String book_agency_name static constraints = { book_agency_name(unique:['mm_author_id','mm_book_id']) } static belongsTo = [authors:Author, books:Book] } 

but getting the following error:

Called: org.codehaus.groovy.grails.validation.exceptions.ConstraintException: Exception caused by applying the restriction [unique] for the class [class content_hub_admin.mm_author_books] for the value [[mm_author_id, mm_book_id]]: Scope [unique] property [name ] of the class [class content_hub_admin.mm_author_books] must be a valid class property name in content_hub_admin.mm_author_books $ _clinit_closure1.doCall (mm_author_books.groovy: 6) in content_hub_admin.mm_author_books $ _clinit_closure1.doCall_doCall_doColl_Down_Doll_Doll_Download_Download

Thanks and Regards

rsheyeah

+4
source share
1 answer

the mm_author_books class (preferably the name AuthorBookRelationship) does not have the mm_author_id and mm_book_id attributes. Try the following:

 class AuthorBookRelationship { String bookAgencyName static constraints = { bookAgencyName(unique:['author','book']) } static belongsTo = [author:Author, book:Book] //only one author and one book } } 
+4
source

Source: https://habr.com/ru/post/1343623/


All Articles