Bookshelf.js save one to many relation

2019-09-14 13:35发布

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条回答
一纸荒年 Trace。
2楼-- · 2019-09-14 14:01

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

查看更多
登录 后发表回答