Browse Source

update mysql8

Willin Wang 3 years ago
parent
commit
d38cd2c924
2 changed files with 59 additions and 5 deletions
  1. 1 4
      README.md
  2. 58 1
      basic/db/mysql8.md

+ 1 - 4
README.md

@@ -31,10 +31,7 @@
 
 2016.8.3 晚写下了本书的第一行话,当时想的名字为《可替代的团队领袖培养计划》,其寓意是希望这些知识经验在团队内部分享,能够培养出更优秀的人才,每个人都能够替代我做得更好。如果能够因此有所建树,则将会成为不可替代的团队领袖。
 
-源码:
-
-* Github: <https://github.com/willin/leader.js.cool>
-* OSChina: <https://gitee.com/willin/leader.js.cool>
+源码: <https://github.com/willin/leader.js.cool>
 
 欢迎进行反馈交流。同时非常期待您在 Github 上 Follow 我 ([@willin](https://github.com/willin)).
 

+ 58 - 1
basic/db/mysql8.md

@@ -101,9 +101,55 @@ main();
 
 其他示例可以参考项目: <https://github.com/shiwangme/mysql8-x-devapi-demo>
 
+## Tips
+
+### Count / 记录总数
+
+Collection 总记录数:
+
+```js
+const session = await mysqlx.getSession().then((session) => session.getSchema('SCHEMA_NAME').getCollection('COLLECTION_NAME'));
+const total = await session.count();
+```
+
+根据条件查询的结果条数:
+
+```js
+const counter = await session.find().fields(['COUNT(1) as count']).execute();
+const total = counter.fetchOne().count;
+```
+
+### Pagination / 分页
+
+以 `Koa` 分页请求为例:
+
+```js
+const { page, size } = ctx.query;
+const session = await Card.getSession();
+
+// 计算页数
+// const counter = await session.find().fields(['COUNT(1) as count']).execute();
+// const total = counter.fetchOne().count;
+const total = await session.count();
+
+const pages = Math.ceil(total / size);
+
+// 执行 Select
+const query = session
+  .find()
+  .sort(['$.created_at DESC'])
+  .limit(size)
+  .offset((page - 1) * size);
+
+const result = await query.execute();
+const list = result.fetchAll();
+
+ctx.success({ page, size, total, pages, list });
+```
+
 ## Model 封装
 
-封装 `Add`、`Modify`、`Remove`和`getSession`,不包含 `Find `。
+封装 `Add`、`Modify`、`Remove`、`FindOne`和`getSession`,不包含 `Find `。
 
 
 ### Utils.js
@@ -176,6 +222,17 @@ class Model {
     // }
   }
 
+  async findOne(key, val) {
+    const session = await mysqlx.getSession();
+    const db = session.getSchema(DB_NAME).getCollection(this.TABLE);
+    return db
+      .find(`${key} = :${key}`)
+      .bind(key, val)
+      .limit(1)
+      .execute()
+      .then((x) => x.fetchOne());
+  }
+
   async modify(id, item) {
     const session = await mysqlx.getSession();
     const db = session.getSchema(DB_NAME).getCollection(this.TABLE);