5

我是 CompoundJS 的新手,在与 jugglingDB 建立一对多关系时遇到了问题。我使用 MySQL 作为数据库。

我已经设置了两个模型书和作者。

本书有许多作者。

这是我的schema.js(db/schema.js):

var Book = describe('Book', function () {
    property('title', String);
    property('isbn', String);
    property('authorId', Number);
    set('restPath', pathTo.books);
});

var Author = describe('Author', function () {
    property('name', String);
    property('authorId', Number);
    set('restPath', pathTo.authors);
});

我将关系放在模型/Book.js 中。这是我的Book.js(模型/Book.js):

module.exports = function (compound, Book) {
  Book.hasMany(compound.models.Author,   {as: 'author',  foreignKey: 'authorId'});
};

这是我的Author.js(模型/Author.js):

module.exports = function (compound, Author) {
 Author.belongsTo(compound.models.Book, {as: 'books', foreignKey: 'authorId'});
};

问题是我无法创建这些关系。当我检查表时,表中没有设置外键。

我从模型 Book.js 和 Author.js 中删除关系并将关系放入 schema.js 本身

之后 schema.js 看起来像这样:

var Book = describe('Book', function () {
    property('title', String);
    property('isbn', String);
    property('authorId', Number);
    set('restPath', pathTo.books);
});

var Author = describe('Author', function () {
    property('name', String);
    property('authorId', Number);
    set('restPath', pathTo.authors);
});

Book.hasMany(Author, {as: 'author',  foreignKey: 'authorId'});
Author.belongsTo(Book, {as: 'books', foreignKey: 'authorId'});

但结果是一样的。

上面的代码有什么问题吗?如果是这样,我该如何解决?

4

1 回答 1

4

看来compoundjs的作者并没有实现Model功能。现在,您的关系应该在模式文件的末尾定义。

此外,您通过存储定义函数的返回值来覆盖方案对象。删除 var Book = 和 var Author =。

并且,foreignKey 是自动创建的。

架构.js:

describe('Book', function () {
    property('title', String);
    property('isbn', String);
    set('restPath', pathTo.books);
});

describe('Author', function () {
    property('name', String);
    set('restPath', pathTo.authors);
});

Book.hasMany(Author, {as: 'author',  foreignKey: 'authorId'});
Author.belongsTo(Book, {as: 'books', foreignKey: 'authorId'});

更新:

哦。您的问题不是定义关系,而是使用它们。jugglingdb 的文档对此不是很清楚。为了建立关系,您必须使用以下格式:有关更多信息,请参阅 DOCS:https ://github.com/1602/jugglingdb

Author.find(id_here_as_string, function(err, author_record){
  book_record = new Book({
    title: 'whatever'
    isbn: 'again whatever here'
  });
  book_record.author(author_record);
  book_record.save()
})

或者

Author.find(id_here_as_string, function(err, author_record){
  book_record = author_record.books.build({
    title: 'whatever'
    isbn: 'again whatever here'
  });
  book_record.save()
})
于 2013-03-06T19:58:26.490 回答