Persistence.js在两个方向上添加多对多

时间:2013-03-03 13:58:59

标签: javascript

使用persistence.js我有两个实体(Foo,Bar)形成多对多关系(N:M)。到目前为止,我只能让它在一个方向上添加许多"",即Foo的一个实例可以添加多个Bars,但是在这种关系中使用的任何Bar实例都不能反过来拥有很多Foos。但任何新的Bar实例都可以再次拥有许多Foos。是否可能,如果是这样,如何在两个方向上添加许多实体""?或者我必须像在RDB中那样使用联结表(N:M => 1:N M:1)?

var foo0, foo1, foo2, bar0, bar1, bar2

Foo = persistence.define( 'Foo', { val: 'TEXT' } )
Bar = persistence.define( 'Bar', { val: 'TEXT' } )
Foo.hasMany( 'bars', Bar, 'foo' )
Bar.hasMany( 'foos', Foo, 'bar' )

persistence.store.memory.config(persistence);
persistence.schemaSync();

foo0 = new Foo( { val : 'foo0' } )
foo1 = new Foo( { val : 'foo1' } )
foo2 = new Foo( { val : 'foo2' } )
bar0 = new Bar( { val : 'bar0' } )
bar1 = new Bar( { val : 'bar1' } )
bar2 = new Bar( { val : 'bar2' } )
foo1.bars.add( bar0 )
foo2.bars.add( bar0 ) // NOTE: already added to DB with statement above => does nothing
foo2.bars.add( bar1 )
bar1.foos.add( foo0 )
bar2.foos.add( foo0 ) // NOTE: already added to DB with statement above => does nothing
bar2.foos.add( foo1 )

persistence.flush( function () {
    Foo.all().each( function ( foo ) {
        foo.bars.list( function ( bars ) {
            console.log( "Foo " + foo.val + ": " )
            _.each( bars, function ( bar ) { console.log( bar.val ) } )
        } )
    } )

    Bar.all().each( function ( bar ) {
        bar.foos.list( function ( foos ) {
            console.log( "Bar " + bar.val + ": " )
            _.each( foos, function ( foo ) { console.log( foo.val ) } )
        } )
    } )

    Bar.all().list( function ( bars ) { foo0.bars = bars } )
    // => "Uncaught Error: not yet supported"
} )

1 个答案:

答案 0 :(得分:2)

1。 inverseProperties必须是相同的

Foo.hasMany( 'bars', Bar, 'foos' )
Bar.hasMany( 'foos', Foo, 'bars' )

2。 每当一个实体添加另一个实体时,都会插入     数据库并自动交叉引用

  foo0 = new Foo { val: 'foo0: not used at all' }
  foo1 = new Foo { val: 'foo1: has bar0, not added by others' }
  foo2 = new Foo { val: 'foo2: cross-add bar1' }
  foo3 = new Foo { val: 'foo3: adds bar1 again' }
  foo4 = new Foo { val: 'foo4: adds multiple' }
  foo5 = new Foo { val: 'foo5: added by bar4 only' }
  bar0 = new Bar { val: 'bar0' }
  bar1 = new Bar { val: 'bar1: cross-add foo2, used again in foo3' }
  bar2 = new Bar { val: 'bar2: added by foo4 #1' }
  bar3 = new Bar { val: 'bar3: added by foo4 #2' }
  bar4 = new Bar { val: 'bar4: added by foo4 #3, has foo5'}

  foo1.bars.add bar0
  foo2.bars.add bar1
  foo3.bars.add bar1
  foo4.bars.add bar2
  foo4.bars.add bar3
  foo4.bars.add bar4

  bar1.foos.add foo2
  bar4.foos.add foo5

3。 然而,当使用addAll()时,情况并非如此,这需要通过持久性本身或其他实体添加

foo4b = new Foo { val : 'foo4b: copies bars from foo4' }
foo4.bars.list ( bars ) ->
        foo4b.bars.addAll bars
        persistence.add foo4b # choose one,
        # bar4.foos.add foo4b # either works