2017-03-22 79 views
0

在我當前的項目中,我創建了一個Gallery Service,我現在要實現一個搜索功能,用戶可以通過選擇不同的過濾器來搜索特定的圖像。在後端,許多濾鏡被分配給圖像。在Sequelize關聯中搜索多個值

我的問題是,當我給多個過濾器,以我的相冊服務(例如下面filterIDs:23,42),它返回它包括過濾#23過濾器#這些圖像42兩者。我期望只獲取包含兩個ID的圖像。

picture.model.js

sequelize.define("Picture", { 
    //... 
    picturePath: { 
    type: DataTypes.STRING 
    } 
}, { 
    classMethods: { 
    associate: function(models) { 
     Picture.belongsToMany(models.Filter, { as: 'filters', through: 'PictureFilter' }; 
    } 
} 

filter.model.js

sequelize.define("Filter", { 
    //... 
    name: { 
    type: DataTypes.STRING 
    } 
} 

我試一下查詢

model.Picture.findAndCountAll({ 
    where: { 
    $ne: null 
    }, 
    include: [ 
    { 
     model: models.Filter, 
     as: 'filters', 
     where: { 
     id: { 
      $in: [23, 42] 
     } 
     } 
    } 
    ] 

經驗的結果:

[ 
    { 
     ..., 
     "rows": [ 
     { 
      ..., 
      "filters": [ 
      { 
       "id": 23, 
       ... 
      } 
      ] 
     }, 
     { 
      ..., 
      "filters": [ 
      { 
       "id": 23, 
       ... 
      }, 
      { 
       "id": 42, 
       ... 
      } 
      ] 
     } 
     ] 
    } 
    ] 

預期結果:

[ 
    { 
     ..., 
     "rows": [ 
     { 
      ..., 
      "filters": [ 
      { 
       "id": 23, 
       ... 
      }, 
      { 
       "id": 42, 
       ... 
      } 
      ] 
     } 
     ] 
    } 
    ] 

預先感謝您!

回答

-1

使用$contains,而不是$in見下面的例子:

id: { 
    $contains: [23, 42] 
}