20130515-Grails In Action-3、建模(05小节)
来源:互联网 发布:python培训视频 编辑:程序博客网 时间:2024/05/17 04:36
上一节了解了1:m的问题,现在解决最棘手的m:n的问题
一般的社交网站上的post都有分类标签,一个post可以有多个标签,同样一个标签也可以打到多个post上。
比如使用场景如下:
- 一个用户可以创建多个标签
- 一个帖子可以打上多个标签,并且每个标签可能打在多个帖子上
根据这个场景,我们可以看到User和Tag是1:m的关系,Post和Tag是m:n的关系,下面我们就着手建立这两个关系
1、创建Tag对象
1 package com.grailsinaction 2 3 class Tag { 4 5 String name 6 User user 7 8 static constraints = { 9 name(blank: false)10 }11 }
2、首先建立User和Tag的1:m关系
修改User
static hasMany = [ posts : Post, tags : Tag ]
这句代表一个User可以有多个Tag,也可以有多个Post
修改Tag
static belongsTo = [ User ]
这句代表级联关系,当User删除了依附在User上的Tag也一并删除。
3、建立Tag和Post的m:n关系
修改Post
static hasMany = [ tags : Tag ]
修改Tag
static hasMany = [ posts : Post ]
最后定义一个维护端,如:当post实体被删除时,依附在被删除的post实体上的tag就没有存在的意义了,也需要一并删除
修改Tag
static belongsTo = [ User, Post ]
4、现在User、Profile、Post、Tag之间的关系已经建立好了:
User-Profile:1:1
User-Post:1:m
User-Tag:1:m
Post-Tag:m:n
5、最后测试一下多对多关系的数据操作
打开PostIntegrationTests类,增加测试方法testPostWithTags
1 @Test 2 void testPostWithTags() { 3 def user = new User(userId: 'joe', password: 'secret').save() 4 def tagGroovy = new Tag(name: 'groovy') 5 def tagGrails = new Tag(name: 'grails') 6 user.addToTags(tagGroovy) 7 user.addToTags(tagGrails) 8 9 def tagNames = user.tags*.name10 assertEquals([ 'grails', 'groovy'] , tagNames.sort())11 12 def groovyPost = new Post(content: "A groovy post")13 user.addToPosts(groovyPost)14 groovyPost.addToTags(tagGroovy)15 assertEquals 1, groovyPost.tags.size()16 17 def bothPost = new Post(content: "A groovy and grails post")18 user.addToPosts(bothPost)19 bothPost.addToTags(tagGroovy)20 bothPost.addToTags(tagGrails)21 assertEquals 2, bothPost.tags.size()22 }
- 20130515-Grails In Action-3、建模(05小节)
- 20130515-Grails In Action-3、建模(01小节)
- 20130515-Grails In Action-3、建模(02小节)
- 20130515-Grails In Action-3、建模(03小节)
- 20130515-Grails In Action-3、建模(04小节)
- 20130516-Grails In Action-3、建模(06小节)
- 20130516-Grails In Action-4、让模型工作(05小节)
- 20130516-Grails In Action-4、让模型工作(01小节)
- 20130516-Grails In Action-4、让模型工作(02小节)
- 20130516-Grails In Action-4、让模型工作(03小节)
- 20130516-Grails In Action-4、让模型工作(04小节)
- 20130517-Grails In Action-4、让模型工作(06小节)
- Grails in Action:完成啦
- 《Spring Boot in Action》【6. Grails】
- grails obtain controller action
- ActiveMQ in Action(3)
- ActiveMQ in Action(3)
- ActiveMQ in Action(3)
- 20130515-Grails In Action-3、建模(01小节)
- win32 sdk inputbox 输入框
- 20130515-Grails In Action-3、建模(02小节)
- 20130515-Grails In Action-3、建模(03小节)
- 20130515-Grails In Action-3、建模(04小节)
- 20130515-Grails In Action-3、建模(05小节)
- 20130516-Grails In Action-3、建模(06小节)
- dp之一维的最大字段和算法
- 20130516-Grails In Action-4、让模型工作(01小节)
- 20130516-Grails In Action-4、让模型工作(02小节)
- 20130516-Grails In Action-4、让模型工作(03小节)
- 20130516-Grails In Action-4、让模型工作(04小节)
- 20130516-Grails In Action-4、让模型工作(05小节)
- 20130517-Grails In Action-4、让模型工作(06小节)