Bookshelf.js save one to many relation

2019-09-14 14:08发布

问题:

I am trying to save a one to many relation My models are

Foo

foo = bookshelf.Model.extend({
        tableName: 'foo',
        bar: function () {
            return this.hasMany('bar', 'barId');
        }

Bar

bar = bookshelf.Model.extend({
        tableName: 'bar',
        foo: function () {
            return this.belongsTo('foo', 'barId');
        }

What I am trying to do

var Foo = { id: 7 }
new Bar({ blah: blah.val  })
                .foo()
                .attach(foo);

The error I am getting

(intermediate value).foo().attach is not a function

Any help will be appreciated.

回答1:

I don't think you can save data like that. I assume that the table bar has foo_id column, so all you need to do is

new Bar().save({ blah: blah.val, foo_id: Foo.id}).then(function(){});