如何解析、持久化和检索标签以空格分隔的字符串?

发布于 2024-07-07 21:23:23 字数 257 浏览 5 评论 0原文

我的数据库由 3 个表组成(一张用于存储所有项目,一张用于存储标签,一张用于存储两者之间的关系):

表:Post 列:PostID、名称、描述

表:标签 列:TagID、名称

表:PostTag 列:PostID、TagID

将空格分隔的字符串(例如“smart fun Wonder”)保存到上面显示的 3 个数据库表中的最佳方法是什么?

最终我还需要检索标签并将其再次显示为字符串。 谢谢!

My database consists of 3 tables (one for storing all items, one for the tags, and one for the relation between the two):

Table: Post
Columns: PostID, Name, Desc

Table: Tag
Columns: TagID, Name

Table: PostTag
Columns: PostID, TagID

What is the best way to save a space separated string (e.g. "smart funny wonderful") into the 3 database tables shown above?

Ultimately I would also need to retrieve the tags and display it as a string again. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

彩虹直至黑白 2024-07-14 21:23:23

粗略地说,是这样的:

class Post {
    static hasMany [tags:Tag]
}

class Tag {
    static belongsTo = Post
    static hasMany [posts:Post]
}

class someService {

    def createPostWithTags(name, desc, tags) {      
        def post = new Post(name: name, desc: desc).save()
        tags.split(' ').each { tagName ->
            def tag = Tag.findByName(tag) ?: new Tag(name: tagName)
            post.addToTags(tag).save()
        }       
    }

}

Roughly, something like this:

class Post {
    static hasMany [tags:Tag]
}

class Tag {
    static belongsTo = Post
    static hasMany [posts:Post]
}

class someService {

    def createPostWithTags(name, desc, tags) {      
        def post = new Post(name: name, desc: desc).save()
        tags.split(' ').each { tagName ->
            def tag = Tag.findByName(tag) ?: new Tag(name: tagName)
            post.addToTags(tag).save()
        }       
    }

}
家住魔仙堡 2024-07-14 21:23:23

如果您有一个标签表,那么每个标签不是都有一行吗?

tag.id = 1; tag.name = 'smart'
tag.id = 2; tag.name = 'funny'
tag.id = 3; tag.name = 'wonderful'

在 Groovy/Grails 中,您可以将它们作为列表检索,可能会将它们连接到一个空格分隔的列表中以供显示。

除非我真的误解了这个问题,Groovy/Grails/GORM 将使用默认脚手架很少或根本不需要代码来处理这个问题,不需要真正的编码。

If you have a Tag Table, wouldn't you have a row for each Tag?

tag.id = 1; tag.name = 'smart'
tag.id = 2; tag.name = 'funny'
tag.id = 3; tag.name = 'wonderful'

In Groovy/Grails, you'd retrieve them as a list, possibly concatenating them into a space separated list for display.

Unless I'm really misunderstanding the question, Groovy/Grails/GORM will handle this with little or no code with the default scaffolding, no real coding required.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文