我正在建立一个社交网站,它有一个像facebook这样的墙,用户可以发布状态,图片和内容。为用户建造一堵墙并不难。我有这样的结构。
Wall
{
Id,
ToUserId (BigInt) (Owner of wall)
ByUserId (The person who is posting)
Content (message, pic or something else)
more fields....
}
这个墙只适合用户,我不能重复使用它,例如,我认为网站会有 其他对象也像Pages,Groups等,所以所有对象都有Wall。我不想为每面墙创建单独的桌子。
然后我想,我可以使用ObjectId而不是ToUserId,我的结构将是这样的。
Wall
{
Id,
ObjectId (BigInt)(PageId/UserId/GroupId (one of them))
ByUserId (The person who is posting)
Content (message, pic or something else)
more fields....
}
由于我在表格中使用“增量”字段,因此页面可以具有用户具有的相同ID。所以这又是一个问题。
接下来,我想,我的对象应该是字符串类型
Wall
{
Id,
ObjectId (string(10))(PageId/UserId/GroupId (one of them))
ByUserId (The person who is posting)
Content (message, pic or something else)
more fields....
}
现在对于用户,我会在数字上附加“U”,因此对象ID将为“1U”,“2U”,对于页面,它们将为“1P”,“2P”和组为“1G”, “2G”。
但我仍然没有说服力,想听听专家的意见。
更新
谢谢大家,我遇到的问题是,如何为所有类型的墙壁保留一张桌子。
A wall for a User
A Wall for a Page
A Wall for a Group
如果你看看facebook,它的一面墙或至少,我想要构建它,所以它应该附加到任何对象(对用户,页面或组或任何东西)。
我希望现在更有意义。
答案 0 :(得分:0)
我会为每个可能的参考找到单独的可空字段。这也允许您使用外键,如果您需要,您甚至可以进行检查约束,因此所有行必须只有一个参考定义。我绝对不建议去寻找那个字符串ID的想法 - 对它进行连接是无效的。
create table [Posts]
(
[ID] int not null identity(1, 1),
[ID_FromUser] int not null,
[ID_ToUser] int null,
[ID_ToPage] int null,
[ID_ToGroup] int null,
[Content] nvarchar(max) not null,
-- more stuff
constraint [FK_Posts_FromUser] foreign key ([ID_FromUser]) references [Users]([ID]),
constraint [FK_Posts_ToUser] foreign key ([ID_ToUser]) references [Users]([ID]),
constraint [FK_Posts_ToPage] foreign key ([ID_ToPage]) references [Pages]([ID]),
constraint [FK_Posts_ToGroup] foreign key ([ID_ToGroup]) references [Groups]([ID]),
constraint [PK_Posts] primary key ([ID])
)
答案 1 :(得分:0)
我不明白为什么你要创造某种"字符串"参考结构。这看起来并不像关系"。
这个怎么样。
用户有许多 帖子。
用户有一个 墙。
帖子有一个 墙。
帖子有一个 用户。
墙有许多 帖子。
墙有一个 用户。
POCO(因为我不能为编写SQL而烦恼)
public class User
{
public int UserId { get; set; }
public ICollection<Post> Posts { get; set; } // the Posts this user has written. Could be against different Wall's
public Wall Wall { get; set; } // the User's wall.
}
public class Post
{
public int PostId { get; set; }
public User User { get; set; } // the User who wrote the post.
public Wall Wall { get; set; } // the Wall this Post belongs to.
}
public class Wall
{
public int WallId { get; set; }
public ICollection<Post> Posts { get; set; } // all the posts on this Wall.
}
假设: