2016-08-19 20 views
0

我有兩個型號:如何使用withRelated獲取一組模型的數據?

const Post = Bookshelf.Model.extend({ 
    tableName: 'post', 
    tags: function() { 
    return this.belongsToMany(Tag) 
    } 
}); 

const Tag = Bookshelf.Model.extend({ 
    tableName: 'tag' 
}); 

我想獲得標籤的Post集合。

我曾嘗試:

const Tags = new Bookshelf.Collection([ 
    Post.forge({ 
     id: 1 
    }), 
    Post.forge({ 
     id: 2 
    }) 
    ]) 
    .fetch({ 
    withRelated: [ 
     'tags' 
    ] 
    }) 
    .then((collection) => { 
    console.log('collection', collection.toJSON()); 
    }); 

這給出了一個錯誤:

Unhandled rejection Error: ER_BAD_TABLE_ERROR: Unknown table 'undefined'

我假設這個錯誤是因爲Bookshelf.Collection不承認第一個參數是模型列表。然而,documentation表明它是一個預期的輸入:

new Collection([models], [options]) 

回答

0

這工作:

PostModel 
    .query('where', 'id', 'in', [1]) 
    .fetchAll({ 
    withRelated: [ 
     'badges' 
    ] 
    }) 
    .call('toJSON'); 

它導致一個查詢:

select 
    `badge`.*, 
    `badge_post`.`post_id` as `_pivot_post_id`, 
    `badge_post`.`badge_id` as `_pivot_badge_id` 
from 
    `badge` 
inner join 
    `badge_post` on `badge_post`.`badge_id` = `badge`.`id` 
where 
    `badge_post`.`post_id` in (?, ?, ?) 
相關問題