我应该为我的Gorm表添加什么其他属性



我的目标是简单地连接三个表(对不起,我对sql的了解有限(

我正在建立一个像Patreon这样的社区平台,每个社区都可以有不同的计划(免费、付费(

示例代码:

type User struct {
Communities []Community `gorm:"many2many:user_communities" json:"communities"`
}
type Community struct {
UserID `json:"userID"`
Users []User `gorm:"many2many:user_communities" json:"users"`
Plans []Plan `json:"plans"`
// How do i add another attirbute to check for user with different plan?
}
type Plan struct {
CommunityID uint `json:"communityID"`
Name string `json:"name"`
Price string `json:"price"`
}

基于上述模型

  1. 一个用户可以加入多个社区
  2. 一个社区可以有多个用户
  3. 一个用户可以拥有一个社区(创建者(
  4. 对于每个社区,一个用户可以加入不同的计划(免费、付费(

我更专注于如何解决4号

所以这里的问题是,我应该在我的社区表中添加什么来区分以免费计划或付费计划加入的用户?

因为我只能根据免费或付费计划查询属于特定社区的用户,而不能查询属于该社区的用户。

示例查询

// Find whether that user belongs to a community
if err := database.Mysql.Table("users u").Joins("JOIN user_communities uc ON u.id = uc.user_id").Where("u.id = ? AND uc.community_id = ?", userID, communityID).Select("1").Scan(&found).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "error happened"})
return
}

一种方法是使计划成为多对多表的一部分。

我真的不知道gorm,但在普通SQL中,它可能看起来像这样。

架构:

create table appUser (
id serial not null,
name text not null,
primary key (id)
);

create table Community (
id serial not null,
owner_id int not null,
name text not null,
primary key (id),
foreign key (owner_id) references appUser(id)
);
create table plan (
id serial not null,
community_id int not null,
name text not null,
price float not null,
primary key (id),
foreign key (community_id) references Community(id)
);

create table UserCommunity (
user_id int not null,
community_id int not null,
plan_id int not null,
primary key (user_id, community_id),
foreign key (plan_id) references plan(id)
);

用法:

insert into appUser (name) values ('maria'), ('jose'), ('clara');
insert into Community (name, owner_id) values ('community1', 1);
insert into plan (community_id, name, price) values 
(1, 'free', 0.0), (1, 'paid', 10.0);
insert into UserCommunity (user_id, community_id, plan_id) values
(2, 1, 1), (3, 1, 2);
select
appUser.name as "user",
community.name as "community",
plan.name as "plan"
from appUser
join UserCommunity on appUser.id = UserCommunity.user_id
join Community on Community.id = UserCommunity.community_id
join plan on plan.id = UserCommunity.plan_id
where plan.name = 'paid';

Fiddle:https://dbfiddle.uk/?rdbms=postgres_13&fiddle=bd37832969396a40944f40ef17f18465

最新更新