我有几个具有多对一关系的mysql表,它使用关系的映射表。如下所示
book_type_map
Column Datatype
book_id Char(36)
book_type_id Char(36)
book_type
Column Datatype
book_type_id Char(36)
book_type Text
default TinyInt(1)
books
Column Datatype
book_id Char(36)
正如您所看到的,book
表或book_type
表没有相互引用的列,我需要能够从book_type
访问book
。这些是Book
和BookType
class Book {
String id
BookType bookType
static mapping = {
table 'books'
id column: 'book_id', generator: 'uuid2'
bookType joinTable: [ name: 'book_type_map',
key: 'book_id',
column: 'book_type_id']
}
}
class BookType {
String id
String type
Boolean default
static mapping = {
table 'book_type'
id column: 'book_type_id', generator: 'uuid2'
type column: 'book_type'
}
}
当我运行此操作时,当我执行Book.findAll()
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:'字段列表'中的未知列'this_.book_type_id'
我认为我的映射不正确。如果有人能指出我正确的方向,我会很感激。
答案 0 :(得分:0)
一般来说,连接表只适用于一对多或多对多关系。在这个例子中,Book只能有一个BookType,那为什么需要一个连接表呢?你只需要一个包含BookTypeId的列。
我认为你在寻找的是:
class Book {
String id
static hasMany = [bookType: BookType]
static mapping = {
table 'books'
id column: 'book_id', generator: 'uuid2'
bookType joinTable: [ name: 'book_type_map',
key: 'book_id',
column: 'book_type_id']
}
}
有关详细信息,请参阅docs
修改强>
如果你在这个表结构上设置了你可以翻转关系(不是这个的粉丝)。这个结构对我来说并没有多大意义,但是会起作用:
class Book {
String id
static mapping = {
table 'books'
id column: 'book_id', generator: 'uuid2'
}
}
class BookType {
String id
String type
Boolean default
static hasMany = [books: Book]
static mapping = {
table 'book_type'
id column: 'book_type_id', generator: 'uuid2'
type column: 'book_type'
books joinTable: [ name: 'book_type_map',
key: 'book_type_id',
column: 'book_id']
}
}