通过hasMany关系查询js查询

时间:2016-07-31 19:28:30

标签: mysql node.js express sequelize.js pg

UPDATED ::::我正在尝试根据我从客户端收到的搜索字词返回用户列表。用户有很多技能。我想通过在所有可能的用户字段中搜索该术语来返回所有用户,其中包括技能标题。

我的表和关系在db文件中,这就是为什么你会看到db.Skill

////// db File
User.belongsToMany(Skill, {through: 'UserSkills', foreignKey: 'mentorId'});
Skill.belongsToMany(User, {through: 'UserSkills', foreignKey: 'skillId'});

////// model file
exports.learnerSearchMentors = function(req, res, term){
db.User.findAll({
where: {
$or: [

      { username       : { $like: '%' + term + '%'}},
      { firstname      : { $like: '%' + term + '%'}},
      { lastname       : { $like: '%' + term + '%'}},
      { email          : { $like: '%' + term + '%'}},
      { phone          : { $like: '%' + term + '%'}},
      { description    : { $like: '%' + term + '%'}},
      {'$skills.title$': { $like: '%' + term + '%'}}
    ]
  },
  include : [{
               model : db.Skill, {through: 'UserSkills'},
               as: 'skills'
            }]
})
.then(function(mentors){
    console.log("line 58: list of found mentors by term");
    res.status(200).send(mentors)
})
.catch(function(err){
    console.error(err.message);
    res.status(500).send(err.message);
});
}

1 个答案:

答案 0 :(得分:0)

为了访问parent where子句包含列中包含的表,如$includedTable.column$

在您的情况下,查询将如下所示:

db.User.findAll({
  where: {
    $or: [
      {
        username: {
          $like: '%' + term + '%'
        }
      },
      ...
      { 
       '$skills.title$' : {
          $like: '%' + term + '%'
        }
      }
    ]
  },
  include : [{
     model : db.Skill,
     as: 'skills'
  }]
})
.then(function(mentors){
    console.log("line 58: list of found mentors by term");
    res.status(200).send(mentors)
})
.catch(function(err){
    console.error(err.message);
    res.status(500).send(err.message);
});