我目前正在开发一个使用PostgreSQL模式进行多租户(每个租户1个模式)的应用程序。
现在,我遇到了以下问题:我想在不同架构的条目之间建立关系(以便租户可以使用其他租户的某些数据)。
我做了一个小样本项目来更好地解释这一点:
{{ site.baseurl }}
在此示例应用程序中,只能为学生分配同一学校的作业。我想要的是学校可以“共享”一些作业,以便可以将其他学校的学生分配给这些作业(“最大”分配给“作业01”和“作业04”)。
但是,当我想在多对多表上创建外键时,我必须分配一个特定的架构(/*
sample project goal
----------------------
one school per schema
every school has students
every school has assignments
You can assign assignments to students. Those assignments can be from every school.
*/
/* reset */
DROP SCHEMA school1 CASCADE;
DROP SCHEMA school2 CASCADE;
/* create schemas */
CREATE SCHEMA school1;
CREATE SCHEMA school2;
/* create student tables */
CREATE TABLE school1.students(
id serial primary key NOT NULL,
name varchar NOT NULL,
unique(name)
);
CREATE TABLE school2.students(
id serial primary key NOT NULL,
name varchar NOT NULL,
unique(name)
);
/* fill student tables with sample data */
INSERT INTO school1.students ("name")
VALUES ('Max');
INSERT INTO school1.students ("name")
VALUES ('Sarah');
INSERT INTO school1.students ("name")
VALUES ('Jane');
INSERT INTO school2.students ("name")
VALUES ('David');
INSERT INTO school2.students ("name")
VALUES ('Lisa');
INSERT INTO school2.students ("name")
VALUES ('James');
/* create assignments tables */
CREATE TABLE school1.assignments(
id serial primary key NOT NULL,
title varchar NOT NULL,
unique(title)
);
CREATE TABLE school2.assignments(
id serial primary key NOT NULL,
title varchar NOT NULL,
unique(title)
);
/* fill assignment tables with sample data */
INSERT INTO school1.assignments ("title")
VALUES ('Assignment 01');
INSERT INTO school1.assignments ("title")
VALUES ('Assignment 02');
INSERT INTO school1.assignments ("title")
VALUES ('Assignment 03');
INSERT INTO school2.assignments ("title")
VALUES ('Assignment 04');
INSERT INTO school2.assignments ("title")
VALUES ('Assignment 05');
INSERT INTO school2.assignments ("title")
VALUES ('Assignment 06');
/* create assignments_students tables */
CREATE TABLE school1.assignments_students(
student_id int REFERENCES school1.students (id) ON UPDATE CASCADE ON DELETE CASCADE,
assignment_id int REFERENCES school1.assignments (id) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT assignments_products_pkey PRIMARY KEY (assignment_id, student_id)
);
CREATE TABLE school2.assignments_students(
student_id int REFERENCES school2.students (id) ON UPDATE CASCADE ON DELETE CASCADE,
assignment_id int REFERENCES school2.assignments (id) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT assignments_products_pkey PRIMARY KEY (assignment_id, student_id)
);
)。这不是我想要的,因为作业可能来自其他任何学校(嘘)。
我将如何在此处实现此功能?
答案 0 :(得分:0)
有几种方法可以解决此问题
方法1
方法2
头脑风暴上述方法,并分享您对特定模型的问题。