2016-07-31 44 views
0

已更新::::我試圖根據我從客戶端收到的搜索詞返回用戶列表。用戶擁有許多技能。我想通過在所有可能的用戶字段(包括技能標題)中搜索該字詞來返回所有用戶。通過hasMany關係對js查詢進行後綴化

我的表和關係是在一個數據庫文件,這就是爲什麼你會看到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); 
}); 
} 

回答

0

爲了獲得包括表從父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); 
}); 
+0

謝謝Tilekbekov。我必須根據User.belongsToMany(Skill,{through:'UserSkills',foreignKey:'mentorId'})來更改關係。 Skill.belongsToMany(User,{through:'UserSkills',foreignKey:'skillId'});所以我必須通過連接表搜索技能標題 – MB060606