2016-06-12 91 views
2

我使用帆0.12.3的PostgreSQL在Mac OSX 10.3.4(10.10.5),和我試圖實現through association:如何創建關聯?

我已經建立了兩個模型用第三個作爲連接表。當我嘗試測試通過創建一個關係,它是所有的設置我得到這個錯誤:

Uncaught TypeError: Cannot read property 'via' of undefined 

這裏是我的測試摩卡/柴) - 我認爲錯誤實際上是在該方法創建關聯(因爲如果我創建模型的加入作爲一個單獨的稱之爲作品:

describe('with orgs', function() { 
    beforeEach(function(done) { 
     var testEmail = '[email protected]'; 
     var orgName = 'Awesome Org'; 
     Org.create({name:orgName}) 
     .then(function(org) { 
     return User.create({username:testEmail, orgs:[org]}) 
     }) 
     .then(function(user) { 
     done() 
     }) 
     .catch(done); 
    }); 
    it('populates empty list of orgs', function(done) { 
     console.log('about to call find'); 
     User.find().populate('orgs') 
     .then(function(users) { 
     console.log('users', users); 
     var user = users[0] 
     assert.isNotNull(user.orgs); 
     assert.equal(user.orgs.length, 1); 
     done(); 
     }) 
     .catch(done); 
    }); 
    }); 

這裏是我的模型:

user.js的:

module.exports = { 
    attributes: { 
    username : { type: 'email' }, 
    orgs: { 
     collection: 'org', 
     via: 'user', 
     through: 'orgmembership' 
    } 
    } 
}; 

Org.js:

module.exports = { 
    attributes: { 
    name : 'string', 
    users: { 
     collection: 'user', 
     via: 'org', 
     through: 'orgmembership' 
    } 
    }, 
}; 

OrgMembership.js:

module.exports = { 
    tableName: 'org_membership', 
    attributes: { 
    user: { model: 'User', columnName: 'user_id', foreignKey: true}, 
    org: { model: 'Org', columnName: 'org_id', foreignKey: true} 
    } 
}; 

我已爲整個項目上github

我發現這個other stackoverflow question,這似乎是做同樣的事情,並試圖遵循相同的模式,但它不適合我。

我會很感激任何指針或建議。謝謝!

+1

看起來這是水線的錯誤,並已作爲修補[email protected]。我測試了您的項目,並按預期工作。 – particlebanana

回答

-1

Users.js應該是指「用戶」在Org.js「內經」的定義,同樣適用於OrgMembership.js

module.exports = { 
    attributes: { 
    username : { type: 'email' }, 
    orgs: { 
     collection: 'org', 
     via: 'users', 
     through: 'orgmembership' 
    } 
    } 
}; 
+0

設計是每個有組織的成員都應該有一個單一的用戶和一個組織,對於我來說這些在OrgMembership中是複數是沒有意義的。無論如何我都試過了,它不適合我 - 測試仍然失敗。 – Ultrasaurus

+0

這裏是我根據你的建議嘗試的改變:https://github.com/ultrasaurus/sails-many-to-many/commit/2b65e1f294da617693a670541c704a4a04aed4bf – Ultrasaurus

+0

風帆只是試圖引用集合,這是你的物理文件,你已經創建了「org.js」,「user.js」等,所以「collection」值必須與賦予該文件的名稱相匹配。 「通過」分配是表示關聯的屬性,並且也應該明確地匹配模型中定義的字段。 – Luke