2016-05-08 26 views
0

たとえば、次のような2つのテーブルがあります。withRelated本棚を使用して結合テーブルから特定の列を取得する方法

table1 {Id, Name, Description} 
table2 {Id, Table1Id, Name, Amount} 

bookshelfJSの場合、withRelatedのようなものを使用すると、

new table1({Id: 1}) 
.fetchAll({ 
    withRelated: ['Childs']}) 
.then(function(rows) { 
    callback(null, rows); 
}); 

私の結果は次のようなものでした。私はを取得する必要はありません

{results: [{Id: '', Name: '', Description: '', Childs: [{Id: '', Name: '', Amount: 123}]}]} 

はチャイルズリストにをTable1Id。出力にどのような列を指定できますか?

更新
マイモデル;

table1 = bookshelf.Model.extend({ 
     tableName: 'table1', 

     Childs: function() { 
      return this.hasMany(table2, 'Table1Id'); 
     } 
}); 

table2 = bookshelf.Model.extend({ 
     tableName: 'table2', 

     Parent: function() { 
      return this.belongsTo(Table1); 
     } 
}); 

私はTable1Id

new table1({Id: 1}) 
.fetchAll({ 
withRelated: ['Childs':function(qb) { 
    qb.select('Id', 'Name', 'Description'); 
}]}) 
.then(function(rows) { 
     callback(null, rows); 
}); 

を選択していないよ場合は、[]チャイルズのために空を返します。
する必要があります。

new table1({Id: 1}) 
.fetchAll({ 
withRelated: ['Childs':function(qb) { 
    qb.select('Id', 'Table1Id', 'Name', 'Description'); 
}]}) 
.then(function(rows) { 
     callback(null, rows); 
}); 

答えて

2

はよくここのことだ:これはかなり簡単に解決することができますが、あなたが問題になっているテーブルのプライマリIDを選択する必要があり、そうでない場合は本棚が一緒にデータを結びつける方法を知ることができません。 Knex.jsからクエリビルダを取得し、selectメソッド(http://knexjs.org/#Builder-select)を使用することです。

new table1({ 
     Id: 1 
    }) 
    .fetchAll({ 
     withRelated: [{ 
      'Childs': function(qb) { 
       //always select the primary Id of the table, otherwise there will be no relations between the tables 
       qb.select('Id', 'Name', 'Amount'); //Table1Id is omitted! 
      } 
     }] 
    }) 
    .then(function(rows) { 
     callback(null, rows); 
    }); 

が、これはあなたの問題を解決するかどうか、私に教えてください:

はここにあなたのケースのためのソリューションです。あなたのbookshelf.jsファイル内

+0

私が親ではない場合は動作しませんId :(ありがとうございます –

+0

あなたのクエストを更新できますか?あなたは何を試してみることができるように新しいクエリで? – uglycode

1

、あなたtable2のモデルで

bookshelf.plugin('visibility'); 

以下のように可視化プラグインを追加し、

table2 = bookshelf.Model.extend({ 
     tableName: 'table2', 
     hidden: ['Table1Id'], 

     Parent: function() { 
      return this.belongsTo(Table1); 
     } 
}); 

以下のように不要なフィールド(複数可)を非表示について、あなたはより多くを学ぶことができますここからvisibilityプラグイン https://github.com/tgriesser/bookshelf/wiki/Plugin:-Visibility

関連する問題