首页 > 解决方案 > 书架中的SQL过滤器查询作为nodejs中的Laravel

问题描述

我是 node.js 的新手,它是 ORM( bookshelf)。我需要知道如何获取具有任何特定类型的用户。

1)。这里users有多个genres,意味着usershasMany 流派和genresbelongsToMany users

问题)。如何获取所有genres= 1的用户

标签: node.jsormknex.jsbookshelf.js

解决方案


实际上我在书架中需要类似whereHas()(如在 Laravel 中)的东西,但在bookshelf. 但是我通过如下的原始 SQL 查询对其进行了整理,并且按照我的要求工作得很好。

User.forge()
.query(function(query){
   query.whereExists(function(){
       this.select('*').from('genres')
       .join('genres_user', function(){
           this.on('genres.id', '=', 'genres_user.genres_id');
       })
      .whereRaw('users.id = genres_user.user_id')
      .where('genres_id', req.query.genres);
   });
})
.fetchAll({
   withRelated : ['profile', 'posts']
})
.then(function (collection) {
    if(collection == ''){
       res.json({error: true, message:'No user found!', data:{}});
    }

    res.json({error: false, data: collection.toJson()});
})
.catch(function (err) {
   res.status(500).json({error: true, data: {message: err.message}});
});

推荐阅读