如何设计带有发布/草稿表的sql数据库?

Bar*_*icz 4 sql database postgresql publish database-schema

我想知道如何制定博客数据库方案。作者撰写文章并将其发布在博客上。这对于像这样的表来说非常简单

作者、文章、博客

但文章也可以有草稿。读者看不到草稿,文章发表后博客的读者可以看到。已发表的文章可以取消发表,成为草稿。

如何连接

草稿

发布

包含文章和博客表的表?有必要吗?或者只是向 Article 表添加一些列?比如IsPublished之类的?

Sch*_*ern 6

有几种方法可以处理这个问题。一种是在您的内容上添加一个status标志,这对于简单的网站很有用。另一种方法是使用一个连接表,将内容与其显示位置、显示方式和时间连接起来。

对于简单的网站,您只需status在内容表中添加一个标志即可。

create type statuses as enum ('published', 'draft');

create table posts (
    id serial,
    author integer references people(id),
    content text not null,
    ...whatever other data...
    status statuses default 'draft'
);
Run Code Online (Sandbox Code Playgroud)

我使用了PostgreSQL 枚举类型来减少存储空间(不是那么重要),因此拼写错误会被捕获(重要),因此有一个地方可以查看所有可能的状态,而不是随意添加它们(也很重要) )。

然后您可以选择所有已发布的帖子。

select *
from posts
where author = ? and
      status = 'published'
Run Code Online (Sandbox Code Playgroud)

这非常简单,但是显示和内容是结合在一起的。如果您忘记检查该status标志,您将显示草稿帖子。


status标志的一个变体是有一个“发布于”日期。在此之前它不会显示。过了这个时间就会了。

create table posts (
    id serial,
    author integer references people(id),
    content text not null,
    ...whatever other data...
    publish_at datetime default '9999-12-31'
);
Run Code Online (Sandbox Code Playgroud)

publish_at然后您可以通过查看是否小于当前日期时间来检查是否应该显示。

select *
from posts
where author = ? and
      publish_at < current_timestamp
Run Code Online (Sandbox Code Playgroud)

默认情况下,“9999-12-31”所有帖子均默认未发布。这将已发布/草稿与自动发布帖子的能力结合在一起,而无需运行任何额外的代码。


更可靠的解决方案是针对要发布的内容和发布位置建立一个连接表。从同一个posts表开始,但没有status列。

create table posts (
    id serial,
    author integer references people(id),
    content text not null,
    ...whatever other data...
);
Run Code Online (Sandbox Code Playgroud)

比为一个人的博客拥有一个。

create table blogs (
    id serial,
    curator integer references people(id)
);
Run Code Online (Sandbox Code Playgroud)

然后创建一个连接表,将帖子与博客帖子连接起来。

create table blog_posts (
    blog integer references blogs(id),
    post integer references posts(id),
    posted datetime not null default current_timestamp
);
Run Code Online (Sandbox Code Playgroud)

现在,当“发布”某些内容时,它会被插入到blog_posts. 没有状态标志。如果您想查看用户的博客文章...

select *
from blog_posts
join blogs on blogs.id = blog_posts.blog
where blogs.curator = ?
order by posted desc;
Run Code Online (Sandbox Code Playgroud)

这样做的优点是通过向 blog_posts 表添加更多联接表或更多字段,一篇文章可以出现在多个位置。并且没有任何status字段需要记住包含在每个语句中。它要么在连接表中,要么不在。

blog_posts还可以有一个publish_at字段。