好的,我迷路了......我有一个域类Student
和Course
. 班级Course
已定。我没有在表格中添加任何新课程。一个学生可以有很多课程,一个课程可以有很多学生。请看看我有什么,并指导我正确的方式。
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"
}
现在,当我输入新的学生信息时,视图不会爆炸,这很好......但是它保存了学生信息但 joinTableSTUDENT_COURSE
是空白的。我知道不知何故我需要将 studnet 的 PK ID 和课程传递给 joinTable,但我不知道如何以及在哪里。(它在 studentController 下def save()
吗?)
另外,应该是什么.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.
}
}
编辑 2
所以,我在考虑并做一些研究....除非我直接使用 SQL 来STUDENT_COURSE
加入表,否则我需要创建一个单独的域类StudentCourse
并将两者Student
和Course
类映射到StudentCourse
. 那是对的吗?