2017-04-06 64 views
0

獲取信息,我有兩個表:從關聯的表

---id---userid--- and ---id---productid---productname--- 

所以,它是由下面的代碼相關聯:

Product.belongsToMany(User, {through: 'resultingproducts', foreignKey: 'userid'}); 
User.belongsToMany(Product, {through: 'resultingproducts', foreignKey: 'productid'}); 

我試圖讓產品從「產品」爲當前用戶

 Product.sync() 
     .then(() => { 
      Product.findAll({ 
       include: [User], 
       through: { 
        where: { 
         userid: userId 
       } 
     }) 

但此代碼返回所有用戶在db中的產品。 任何人都可以幫助我嗎?

回答

1

你應該真的在查詢用戶模型而不是產品模型。 嘗試將您的代碼更改爲以下內容,以查找與「此用戶」相關的所有產品'相關'。

User.findAll({ 
    include: { 
    model: Product, // Product is Product model 
    through: {attributes: []} // this will remove rows from join table in the result 
    }, 
    where: { userId: userId } // note, where clause is outside 'include' and 'through' 
})