我有一个模型,它代表一个可以由用户在应用程序中保存为草稿的实体。例如,可以在新产品表单中保存为草稿的产品。
我最初的方法是在产品表中创建一个标志
draft
。我开始遇到一些问题,例如必须从表的某些列中删除“not null”。产品有一些字段不能为空(但在草稿中可以为空),我认为从表中删除此约束不好。此外,我还必须在服务中添加新逻辑才能让产品按 draft=false
进行过滤。
我相信创建新表也会导致一些问题,例如代码重复,必须添加逻辑以在创建产品后删除草稿条目。
使用标志还是创建新表,哪一种是最好的方法?
这取决于细节,但通常更好的模式是为通用内容使用一个表格,并为内容的每种复杂状态使用表格。例如,如果您有一些商品可以由不同的卖家出售,该怎么办?
-- This is the general information about the item.
create table items (
id integer primary key,
maker_id integer not null references makers(id),
name text not null,
description text,
price numeric(9,2),
created_at timestamp not null default now()
);
-- This is specific information about the item when sold by a particular seller.
create table items_for_sale (
item_id integer not null references items(id),
seller_id integer not null references sellers(id),
name text not null,
description text not null,
price numeric(9,2) not null,
put_on_sale_at timestamp not null default now(),
unique(item_id, seller_id)
);
通过这种方式,您将拥有一个用于显示商品本身的表格,以及一个描述其销售方式的单独表格。名称、价格和描述可以从商品中复制,也可以为特定商品/卖家拥有自己的名称、价格和描述。例如,该商品可以有建议价格,但每个卖家可以决定自己的价格。
您可以对帖子等内容执行类似的操作。有一张
posts
桌子,还有一张 published
桌子。