node.js - 书架中的SQL过滤器查询作为nodejs中的Laravel
问题描述
我是 node.js 的新手,它是 ORM( bookshelf
)。我需要知道如何获取具有任何特定类型的用户。
1)。这里users
有多个genres
,意味着users
hasMany 流派和genres
belongsToMany users
。
问题)。如何获取所有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}}); });
解决方案
实际上我在书架中需要类似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}});
});
推荐阅读
- python - python 文件 - 谁可以正确打开
- c++ - 传递向量作为参考的正确方法是什么?
- android-studio - 在 Android Studio/IntelliJ 中,如何从代码片段模式切换到表达式模式?
- c# - 在 AspNET Core 中使用 DI
- python - 试图找到一种方法来简化我的代码块
- java - 将返回高/低阈值的最佳图像阈值技术?
- git - 在服务器端复制 git 客户端钩子
- python - 用无限期的while循环调度重复任务有什么根本错误吗?
- java - 如何访问数组中自动生成的java对象的数据?
- javascript - decodeURIComponent 不能从 URL 工作