CompoundJS中的一对多关系

时间:2013-03-05 13:09:35

标签: node.js express railway.js compoundjs

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

我已经设置了两个模型Book and Author。

Book有很多作者。

这是我的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);
});

我把关系放在models / Book.js中。 这是我的Book.js(models / Book.js):

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

这是我的Author.js(models / 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'});

但结果是一样的。

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

1 个答案:

答案 0 :(得分:4)

似乎composjs的作者还没有实现模型功能。现在你的关系应该在模式文件的末尾定义。

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

并且,foreignKey是自动创建的。

schema.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'});

更新

OH。您的问题不是定义关系,而是使用它们。 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()
})

OR

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()
})