首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我应该为我的Gorm表添加其他属性吗?

我应该为我的Gorm表添加其他属性吗?
EN

Stack Overflow用户
提问于 2022-02-13 10:03:06
回答 1查看 76关注 0票数 1

我的目标是简单地连接三个表(对不起,我在sql中的知识有限)

我正在构建一个基于社区的平台,比如Patreon,每个社区都可以有不同的计划(免费,付费)

示例代码:

代码语言:javascript
复制
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"`
}

基于上述模型

一个用户可以加入多个communities

  • One社区,可以有多个用户

  • 一个用户可以拥有一个社区(创建者)

  • ,对于每个社区,一个用户可以加入不同的计划(免费,付费)

我更关注的是如何解决4号问题

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

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

示例查询

代码语言:javascript
复制
// 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
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-13 13:30:59

一种方法是让这个计划成为多到多表的一部分。

我真的不知道gorm,但在普通SQL中,这可能是这样的。

模式:

代码语言:javascript
复制
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)
);

用法:

代码语言:javascript
复制
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';

小提琴:https://dbfiddle.uk/?rdbms=postgres_13&fiddle=bd37832969396a40944f40ef17f18465

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71099598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档