Tôi đang làm theo ví dụ trong Grails in Action. Tôi gặp sự cố khi hiểu chức năng của addTo*()
hoạt động như thế nào.Grails addTo * clarification
Tôi có một miền đơn giản: dùng, Post, Tag với các mối quan hệ sau:
- tài khoản 1-to-M bài
- tài khoản 1-to-M Tag
- bài viết M-to -M Tag
Khi tôi chạy đoạn mã sau (trường hợp đầu tiên):
1. def user = new User(userId: 'joe', password: 'secret').save()
2. def tagGroovy = new Tag(name: 'groovy')
3. def tagGrails = new Tag(name: 'grails')
4. user.addToTags(tagGroovy)
5. user.addToTags(tagGrails)
6.
7. def groovyPost = new Post(content: 'A groovy post')
8. user.addToPosts(groovyPost)
9. groovyPost.addToTags(tagGroovy)
10.
11. User.get(1).tags.each {println it.id + " " + it.name}
12. User.get(1).posts.each {println it.id + " " + it.content + " " + it.dateCreated}
tôi có được điều này:
null grails
null groovy
null A groovy post null
Và nếu tôi thay đổi dòng 4, 5, và 8 đến:
4. user.addToTags(tagGroovy).save(flush: true)
5. user.addToTags(tagGrails).save(flush: true)
8. user.addToPosts(groovyPost).save(flush: true)
tôi có được điều này:
2 grails
1 groovy
1 A groovy post Tue Nov 22 21:00:00 WET 2011
Ai đó có thể giải thích tại sao trong trường hợp đầu tiên các thuộc tính id
và dateCreated
không được lưu giữ?