好吧,我迷路了...我有一个域名类Student
和Course
。类别Course
已设置。我不添加任何新课程到表中。一个学生可以有很多课程,一门课程可以有很多学生。请看看我有什么,并指导我以正确的方式。Grails - 多对多数据持久性(EDITED)
class Student {
String fullName
static belongsTo = [schools: School]
static hasMany = [courses:Course]
static mapping = {
table "STUDENT"
courses joinTable: "STUDENT_COURSE", key: "COURSE_ID"
}
class Course {
String courseName
static hasMany = [students:Student]
static belongsTo = Student
static mapping = {
students joinTable: "STUDENT_COURSE", key: "STUDENT_ID"
}
现在,当我进入新的学生信息,视图不炸毁,所以这是很好的...但它可以节省学生的信息,但joinTable STUDENT_COURSE
是空白。我知道我需要将studnet和course的PK ID传递给joinTable,但我不知道如何以及在哪里。 (它是否在def save()
下的studentController?
另外,
.gsp
应该是什么样子?这是我的,我知道我错了。
(id="coursetags" is jQuery autocomplete id)
我的_form.gsp
输入部分。
<div class="fieldcontain ${hasErrors(bean: studentInstance, field: 'courses', 'error')} required" >
<label for="course">
<g:message code="student.courses.label" default="Course" />
<span class="required-indicator">*</span>
</label>
<g:textField name="course" id="coursetags" required="" value="${course?.course}"/>
我的结果应该是这样的。
STUDENT COURSE STUDENT_COURSE
ID FULLNAME ID COURSENAME STUDENT_ID COURSE_ID
1 John Doe 1 English101 1 1
2 Jane Smith 2 Science101 1 2
2 2
我一直在试图分析这些网站...
http://chrisbroadfoot.id.au/2008/07/19/many-to-many-relationship-mapping-with-gorm-grails/
https://grails.github.io/grails-doc/3.0.x/guide/GORM.html#manyToMany
https://grails.org/wiki/Many-to-Many%20Mapping%20without%20Hibernate%20XML
谢谢。
编辑1
我控制器
class studentController {
@Transactional
def save(Student studentInstance) {
if (studentInstance == null) {
notFound()
return
}
if (studentInstance.hasErrors()) {
respond studentInstance.errors, view:'create'
return
}
def courseID = Course.findByCourseLike(params.course)
studnetInstance.save flush:true
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.created.message', args: [message(code: 'student.label', default: 'Student'), studnetInstance.id])
redirect studentInstance
}
'*' { respond studentInstance, [status: CREATED] }
}
def sID = studentInstance.id //When I println under these, they print the right id numbers.
def cID = courseID.id
student.addToCourses(cID).save() //This is the part that I don't understand.
//I get error saying No such property: student for class.
}
}
EDIT 2 所以,我在想,做一些研究....除非我用SQL直接STUDENT_COURSE
连接表,我需要为StudentCourse
创建单独的域类,并将Student
和Course
类映射到StudentCourse
。那是对的吗?