【问题标题】:SQL filter query in bookshelf as Laravel in nodejs书架中的SQL过滤器查询作为nodejs中的Laravel
【发布时间】:2018-12-04 10:04:32
【问题描述】:

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

1).这里users有多个genres,意思是users有很多流派和genresbelongsToManyusers。

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

  • 下面是我的代码试图实现这一点,但无法得到正确的答案。

    User.forge()
      .query(function(query){
         query.whereExists(function(){
             this.select('*').from('genres')
             .join('genres_user', function(){
                this.on('genres.id', '=', 'genres_user.genres_id');
             })
            .where('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}});
     });
    

【问题讨论】:

  • 如果你知道 Laravel,你应该试试adonisjs.com
  • 感谢您抽出时间,adonis 是一个很棒的框架,但我一定会在 Express 上工作。

标签: node.js orm knex.js bookshelf.js


【解决方案1】:

实际上,我在书架上需要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}});
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 2020-03-16
    相关资源
    最近更新 更多