egg-mysql or ali-rds 能否实现“可有可无”的条件查询写法吗?
- Node Version:
- Egg Version:
- Plugin Name: egg-mysql
- Plugin Version: ^1.0.0
- Platform:
egg-mysql将where条件语句查询封装在对象里,
const type = this.query.type;
const page = this.query.page || 1;
const pageSize = this.query.pageSize || 10;
const pangufe = this.app.mysql.get('pangufe');
const results = yield pangufe.select('log', {
where: {type: type},
columns: ['type', 'ua', 'page', 'error_message', 'create_time'],
orders: [['create_time', 'desc'], ['id', 'desc']],
limit: pageSize,
offset: pageSize * (page - 1)
});
这样还能不能实现 某条件可有可无 的查询? 功能诸如PHP的Yii框架中,若有此条件,则加一个andWhere就好。
$find = LiveContent::find()->with('user');
if (!$this->getLiveUser(self::HOST_ID)) {
$this->addLiveUser(self::HOST_ID);
}
if (User::get('user_id') != self::HOST_ID) {
$find->andWhere(['=', 'status', LiveContent::STATUS_ACTIVE]);
}
if ($searchKey) {
$find->andWhere(['LIKE', 'content', $searchKey]);
}
if ($sort == 'old') {
if ($contentId) {
$find->andWhere(['<', 'content_id', $contentId]);
}
$find->orderBy('content_id DESC');
} elseif ($sort == 'new') {
if ($contentId) {
$find->andWhere(['>', 'content_id', $contentId]);
}
$find->orderBy('content_id ASC');
}
return $find;
可以加链式调用操作。
pangufe.select('log')
.andWhere({status: status})
. orderBy([['create_time', 'desc'], ['id', 'desc']])
苏千大大好,这个功能现在是没有吧? 我一直是自己自学node,也不知道什么是最佳方式。 现在如果要实现这样的功能,是要写多个重复的查询语句吗? 比如:
let results;
if (type) {
results = yield pangufe.select('log', {
where: {type: type}
});
} else {
results = yield pangufe.select('log');
}
ps: 苏千大大博客里最大的那张照片第一排最中间的人是我😳 那年大三,现在都工作一年还是没什么长进。
@cuitianze 网友见面 :)
@fengmk2 粉丝😆
粉丝好多啊
@xudafeng 达峰学长😁
来来来,先把我问题回答了😝
见网友
https://github.com/eggjs/egg/blob/master/docs/source/zh-cn/practice/mysql.md 详细的数据库操作介绍
链接打不开了。。
@xjchenhao 链接改成了这个 https://github.com/eggjs/egg/blob/master/docs/source/zh-cn/tutorials/mysql.md