NodeJS Bookshelf 用户-追随者关系示例

NodeJS Bookshelf Users-Followers Relation Sample

我正在尝试与 Bookshelf 创建用户-关注者关系,但我无法实现它:(

你能给我举个简单的例子吗?

感谢您的宝贵时间:)

SQL:

DROP TABLE IF EXISTS usersfollows;
DROP TABLE IF EXISTS users;

CREATE TABLE users (
    "id" serial NOT NULL ,
    "username" varchar(40) NOT NULL ,
    "email" varchar(255) NOT NULL ,
    "pass" varchar(255)
    PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "users_username" ON users (username);
CREATE UNIQUE INDEX "users_email" ON users (email);
CREATE UNIQUE INDEX "users_hash" ON users (uuid);
CREATE UNIQUE INDEX "users_uuid" ON users (uuid);
SELECT setval('users_id_seq', 18);

CREATE TABLE usersfollows (
    "id" serial NOT NULL ,
    "userId" integer NOT NULL REFERENCES users,
    "followId" integer NOT NULL REFERENCES users,
    PRIMARY KEY ("id")
);

这可能有效:

var User = Bookshelf.model.extend({
    tableName: 'user',
    follows: function() {
        return this.belongsToMany(User, 'usersfollows', 'followId', 'userId');
    },
    followers: function() {
        return this.belongsToMany(User, 'usersfollows', 'userId', 'followId');
    }
});

注:

  • 以上我没有测试过,也没有做过类似的案例(单机多对多table)
  • Bookshelf.js 文档似乎隐含地声明它期望连接 table (usersfollows) 具有复合 PK 而不是单独的 PK。如果您无法修改 table 结构,您可能需要使用 through - 请参阅 Bookshelf.js documentation for belongsToMany.

如果你可以/需要尝试那种复合 PK 的东西,它应该是这样的:

CREATE TABLE usersfollows (
    "userId" integer NOT NULL REFERENCES users,
    "followId" integer NOT NULL REFERENCES users,
    PRIMARY KEY ("userId", "followId")
);

无论如何,我不确定以上是否可行 - 我自己对书架的经验不是很丰富 - 如果行不通,希望更有知识的人给出更好的答案。