douli4337 2019-04-18 18:57
浏览 8

将多对多相关数据集提取到单个结构中

I try to build an RBAC authorization system into an application. Users, roles and permissions are stored in a database. Each role can be assigned to each user. That's why I have a user_account and a role table glued together into a many-to-many relationship by the user_role junction table. Trimmed down, the database setup looks like this:

CREATE TABLE user_account (
    id    uuid NOT NULL DEFAULT uuid_generate_v1mc(),
    email character varying(128) NOT NULL,
    CONSTRAINT user_account_pkey PRIMARY KEY (id),
    CONSTRAINT user_account_email_key UNIQUE (email)
);

CREATE TABLE role (
    id   uuid NOT NULL DEFAULT uuid_generate_v1mc(),
    name character varying(128) NOT NULL,
    CONSTRAINT role_pkey PRIMARY KEY (id),
    CONSTRAINT role_name_key UNIQUE (name)
);

CREATE TABLE user_role (
    user_id uuid NOT NULL,
    role_id uuid NOT NULL,
    CONSTRAINT user_role_pkey PRIMARY KEY (user_id, role_id),
    CONSTRAINT user_role_fkey_user FOREIGN KEY (user_id) REFERENCES user_account (id) ON DELETE CASCADE,
    CONSTRAINT user_role_fkey_role FOREIGN KEY (role_id) REFERENCES role (id) ON DELETE CASCADE
);

Obviously I have set up matching go structs:

type User struct {
    ID    string `db:"id"`
    Email string `db:"email"`
}

type Role struct {
    ID   string `db:"id"`
    Name string `db:"name"`
}

So far so good. Fetching one or more rows individually into the matching go struct is not an issue. But I would prefer to fetch a user and all its assigned roles. The resulting go struct would look something like this:

type User struct {
    ID    string `db:"id"`
    Email string `db:"email"`
    Roles []Role 
}

What I'm asking is: What is the best strategy to fetch the data into the struct?

  1. Fetch the user record with a query, fetch all its assigned roles with another query and build the User struct.

or

  1. Fetch the user record and all its assigned roles with a single query.

I know how to do the first case but struggle with the second one. I'm using sqlx and PostgreSQL. Is it even possible what I try to achieve? If yes, how? Which db tag to use?

My naive query for approach two looks like this, but obviously doesn't work as intended:

SELECT user_account.id, user_account.email, role.id, role.name
  FROM user_account
LEFT OUTER JOIN user_role
  ON user_account.id = user_role.user_id
LEFT OUTER JOIN role
  ON user_role.role_id = role.id

Any suggestions?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本