<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Bookshelf.js 教程 > 原文: [http://zetcode.com/javascript/bookshelf/](http://zetcode.com/javascript/bookshelf/) Bookshelf.js 教程展示了如何使用 Bookshelf.js ORM 在 JavaScript 中對數據庫進行編程。 Bookshelf.js 構建在 Knex 之上。 ## Bookshelf.js Bookshelf.js 是基于 Knex SQL 查詢生成器構建的 Node.js 的 JavaScript ORM。 它支持基于`promise`和傳統的回調接口。 書架提供事務支持,渴望/嵌套渴望的關系加載,多態關聯以及對一對一,一對多和多對多關系的支持。 Bookshelf.js 可與 PostgreSQL,MySQL 和 SQLite3 一起使用。 對象關系映射(ORM)是一種從面向對象的語言訪問關系數據庫的技術。 它是 Python 數據庫 API 的抽象。 在本教程中,我們使用 PostgreSQL。 ## 城市表 我們使用城市表。 `cities_postgresql.sql` ```js DROP TABLE IF EXISTS cities; CREATE TABLE cities(id serial PRIMARY KEY, name VARCHAR(255), population INT); INSERT INTO cities(name, population) VALUES('Bratislava', 432000); INSERT INTO cities(name, population) VALUES('Budapest', 1759000); INSERT INTO cities(name, population) VALUES('Prague', 1280000); INSERT INTO cities(name, population) VALUES('Warsaw', 1748000); INSERT INTO cities(name, population) VALUES('Los Angeles', 3971000); INSERT INTO cities(name, population) VALUES('New York', 8550000); INSERT INTO cities(name, population) VALUES('Edinburgh', 464000); INSERT INTO cities(name, population) VALUES('Berlin', 3671000); ``` ## 安裝 Bookshelf.js 我們安裝書架。 ```js $ node -v v11.5.0 ``` 我們使用 Node 版本 11.5.0。 ```js $ npm init -y ``` 我們啟動一個新的 Node 應用。 ```js $ npm i pg $ npm i knex bookshelf ``` 我們安裝了 PostgreSQL 驅動程序 Knex.js 和 Bookshelf.js。 ## Bookshelf.js計數行 在第一個示例中,我們計算`cities`表中的行數。 `config/db.js` ```js const knex = require('knex')({ client: 'pg', connection: { host: '127.0.0.1', user: 'postgres', password: '', database: 'testdb', charset: 'utf8' } }); module.exports.knex = knex; ``` 在`db.js`文件中,我們定義一個 Knex 客戶端對象。 `model/city.js` ```js const knex = require('../config/db').knex; const bookshelf = require('bookshelf')(knex); const City = bookshelf.Model.extend({ tableName: 'cities' }); module.exports = City; ``` 我們有模型對象。 模型對象映射到數據庫表中的一行。 `count_cities.js` ```js const knex = require('./config/db').knex; const City = require('./model/city'); City.count().then((count) => { console.log(`There are ${count} cities`); }).catch((err) => { console.log(err); }).finally(() => { knex.destroy(); }); ``` 該示例計算`cities`表中的行數。 它使用回調。 ```js $ node count_cities.js There are 8 cities ``` 這是輸出。 `count_cities2.js` ```js const knex = require('./config/db').knex; const City = require('./model/city'); async function countCities() { try { let count = await City.count(); console.log(`There are ${count} cities`); } catch (e) { logger.info(`No data found ${e}`); } finally { knex.destroy(); } } countCities(); ``` 在第二個示例中,我們將`promise`與`async/await`一起使用。 ## Bookshelf.js `fetch()` `fetch()`使用當前在模型上設置的任何屬性來從數據庫獲取模型,以形成選擇查詢。 設置`require`選項后,如果結果為空,則返回的響應將被`NotFoundError`拒絕。 ```js $ npm i winston ``` 在此示例中,我們還使用 Winston 日志記錄模塊。 `fetch_city.js` ```js const knex = require('./config/db').knex; const City = require('./model/city'); const winston = require('winston'); const consoleTransport = new winston.transports.Console() const options = { transports: [consoleTransport] } const logger = new winston.createLogger(options) async function fetch_city() { try { let val = await City.where({ 'name': 'Bratislava' }).fetch({require:true}); // console.log(val.toJSON()); logger.info(val); } catch (e) { logger.info(`No data found ${e}`); } finally { knex.destroy(); } } fetch_city(); ``` 該示例檢索指定的城市。 ```js let val = await City.where({ 'name': 'Bratislava' }).fetch({require:true}); ``` 我們獲取一個名為`'Bratislava'`的模型。 ```js logger.info(val); ``` 我們記錄返回的數據。 ```js $ node fetch_city.js {"message":{"id":1,"name":"Bratislava","population":432000},"level":"info"} ``` 這是輸出。 ## Bookshelf.js `fetch_all` `fetch_all()`使用當前在模型上設置的任何查詢參數從數據庫中獲取模型的集合,以形成選擇查詢。 `fetch_all.js` ```js const knex = require('./config/db').knex; const City = require('./model/city'); async function fetch_all() { try { let vals = await City.fetchAll(); console.log(vals.toJSON()); } catch (e) { console.log(`Failed to fetch data: ${e}`); } finally { knex.destroy(); } } fetch_all(); ``` 該示例檢索所有城市。 ```js let vals = await City.fetchAll(); ``` 我們稱為`fetchAll()`函數。 ```js console.log(vals.toJSON()); ``` 數據以 JSON 格式寫入控制臺。 ```js $ node fetch_all.js [ { id: 1, name: 'Bratislava', population: 432000 }, { id: 2, name: 'Budapest', population: 1759000 }, { id: 3, name: 'Prague', population: 1280000 }, { id: 4, name: 'Warsaw', population: 1748000 }, { id: 5, name: 'Los Angeles', population: 3971000 }, { id: 6, name: 'New York', population: 8550000 }, { id: 7, name: 'Edinburgh', population: 464000 }, { id: 8, name: 'Berlin', population: 3671000 } ] ``` 這是輸出。 ## Bookshelf.js `forge()`輔助函數 Bookshelf 的`forge()`是一個簡單的輔助函數,可在不需要`new`關鍵字的情況下實例化新模型。 `forge_helper.js` ```js const knex = require('./config/db').knex; const City = require('./model/city'); async function fetch_city() { try { let val = await City.forge({ 'id': '4' }).fetch(); console.log(val.toJSON()); } catch (e) { console.info(`No data found ${e}`); } finally { knex.destroy(); } } fetch_city(); ``` 在示例中,我們使用`forge()`幫助器選擇一個城市。 ## Bookshelf.js `save()` 用`save()`保存新模型。 `save_city.js` ```js const knex = require('./config/db').knex; const City = require('./model/city'); async function save_city() { try { let val = await City.forge({ 'name': 'Kyiv', 'population': 2884000}).save(); console.log(val.toJSON()); } catch (e) { console.log(`Failed to save data: ${e}`); } finally { knex.destroy(); } } save_city(); ``` 該示例將保存一個新城市。 ```js $ node save_city.js { name: 'Kyiv', population: 2884000, id: 9 } $ node fetch_all.js [ { id: 1, name: 'Bratislava', population: 432000 }, { id: 2, name: 'Budapest', population: 1759000 }, { id: 3, name: 'Prague', population: 1280000 }, { id: 4, name: 'Warsaw', population: 1748000 }, { id: 5, name: 'Los Angeles', population: 3971000 }, { id: 6, name: 'New York', population: 8550000 }, { id: 7, name: 'Edinburgh', population: 464000 }, { id: 8, name: 'Berlin', population: 3671000 }, { id: 9, name: 'Kyiv', population: 2884000 } ] ``` 這是輸出。 ## Bookshelf.js `orderBy()` `orderBy()`函數按指定的列名和排序順序對檢索到的數據進行排序。 `order`參數是可選的,默認為'ASC'。 `order_by.js` ```js const knex = require('./config/db').knex; const City = require('./model/city'); async function fetch_city() { try { let vals = await City.forge().orderBy('name', 'DESC').fetchAll({require:true}); console.log(vals.toJSON()); } catch (e) { console.log(`Failed to fetch data: ${e}`); } finally { knex.destroy(); } } fetch_city(); ``` 在示例中,我們獲取所有城市,并按名稱降序排列它們。 ```js $ node order_by.js [ { id: 4, name: 'Warsaw', population: 1748000 }, { id: 3, name: 'Prague', population: 1280000 }, { id: 6, name: 'New York', population: 8550000 }, { id: 5, name: 'Los Angeles', population: 3971000 }, { id: 9, name: 'Kyiv', population: 2884000 }, { id: 7, name: 'Edinburgh', population: 464000 }, { id: 2, name: 'Budapest', population: 1759000 }, { id: 1, name: 'Bratislava', population: 432000 }, { id: 8, name: 'Berlin', population: 3671000 } ] ``` 這是輸出。 ## Bookshelf.js 一對一關系 一對一的關系由`hasOne()`和`belongsTo()`函數定義。 `employees_projects.sql` ```js DROP TABLE IF EXISTS employees; DROP TABLE IF EXISTS projects; CREATE TABLE projects(id serial PRIMARY KEY, name VARCHAR(255)); INSERT INTO projects(name) VALUES('Project A'); INSERT INTO projects(name) VALUES('Project B'); INSERT INTO projects(name) VALUES('Project C'); CREATE TABLE employees(id serial PRIMARY KEY, project_id INT REFERENCES projects (id), name VARCHAR(255)); INSERT INTO employees(project_id, name) VALUES(2, 'John Doe'); INSERT INTO employees(project_id, name) VALUES(1, 'Lucia Smith'); ``` 我們有`employees`和`projects`。 員工只能分配到一個項目。 ### Bookshelf.js `hasOne()` `hasOne()`函數定義模型之間的一對一關系。 `hasOne`關系指定表恰好具有另一種對象類型,該對象由另一表中的外鍵指定。 `model/project.js` ```js const knex = require('../config/db').knex; const bookshelf = require('bookshelf')(knex); const Employee = require('./employee'); const Project = bookshelf.Model.extend({ tableName: 'projects', employee: function () { return this.hasOne(Employee); } }); module.exports = Project; ``` `Project`模型包含`hasOne()`函數。 通過查詢項目,我們可以獲取其鏈接的員工。 `model/employee.js` ```js const knex = require('../config/db').knex; const bookshelf = require('bookshelf')(knex); const Employee = bookshelf.Model.extend({ tableName: 'employees' }); module.exports = Employee; ``` 這是`Employee`模型。 `has_one.js` ```js const knex = require('./config/db').knex; const Project = require('./model/project'); async function doQuery() { try { let val = await Project.where({ id: 2 }).fetch({ withRelated: ['employee'] }); console.log(val.toJSON()); } catch (e) { console.log(`Failed to fetch data: ${e}`); } finally { knex.destroy(); } } doQuery(); ``` 在示例中,我們獲取一個項目及其關聯的員工。 ```js let val = await Project.where({ id: 3 }).fetch({ withRelated: ['employee'] }); ``` 指定`withRelated`選項以獲取集合的模型,并希望加載該模型上命名的任何指定關系。 如果沒有此選項,我們將僅獲得沒有關聯員工的項目。 ```js $ node has_one.js { id: 2, name: 'Project B', employee: { id: 1, project_id: 2, name: 'John Doe' } } ``` 這是輸出。 ### Bookshelf.js `belongsTo()`一對一 當一個模型是另一個目標模型的成員時,將使用`belongsTo()`函數。 外鍵在當前(源)模型中定義。 `belongsTo()`函數用于一對一和`one-to-many`關系。 `model/project.js` ```js const knex = require('../config/db').knex; const bookshelf = require('bookshelf')(knex); const Project = bookshelf.Model.extend({ tableName: 'projects' }); module.exports = Project; ``` 這是`Project`模型。 `model/employee.js` ```js const knex = require('../config/db').knex; const bookshelf = require('bookshelf')(knex); const Project = require('./project'); const Employee = bookshelf.Model.extend({ tableName: 'employees', project: function () { return this.belongsTo(Project); } }); module.exports = Employee; ``` `Employee`包含`belongsTo()`函數。 `belongs_to.js` ```js const knex = require('./config/db').knex; const Employee = require('./model/employee'); async function doQuery() { try { let val = await Employee.where({ id: 1 }).fetch({ withRelated: ['project'], require: true }); console.log(val.toJSON()); } catch (e) { console.log(`Failed to fetch data: ${e}`); } finally { knex.destroy(); } } doQuery(); ``` 在該示例中,我們通過其鏈接項目獲取一名雇員。 ```js $ node belongs_to.js { id: 1, project_id: 2, name: 'John Doe', project: { id: 2, name: 'Project B' } } ``` 這是輸出。 ## Bookshelf.js 一對多關系 一對多關系通過`hasMany()`和`belongsTo()`函數定義。 `users_tasks.js` ```js DROP TABLE IF EXISTS tasks; DROP TABLE IF EXISTS users; CREATE TABLE users(id serial PRIMARY KEY, name VARCHAR(255)); INSERT INTO users(name) VALUES('John Doe'); INSERT INTO users(name) VALUES('Lucia Smith'); CREATE TABLE tasks(id serial PRIMARY KEY, user_id INT REFERENCES users (id), name VARCHAR(255)); INSERT INTO tasks(user_id, name) VALUES(1, 'Task A'); INSERT INTO tasks(user_id, name) VALUES(1, 'Task B'); INSERT INTO tasks(user_id, name) VALUES(1, 'Task C'); INSERT INTO tasks(user_id, name) VALUES(2, 'Task D'); INSERT INTO tasks(user_id, name) VALUES(2, 'Task E'); ``` 我們有`users`和`tasks`。 用戶可以執行一個或多個任務。 一個任務只能由一個用戶擁有。 ### Bookshelf.js `hasMany()` `hasMany()`定義了模型之間的一對多關系。 該關系指定當前模型在另一張表中具有一個或多個與該模型的主鍵匹配的行。 `model/user.js` ```js const knex = require('../config/db').knex; const bookshelf = require('bookshelf')(knex); const Task = require('./task'); const User = bookshelf.Model.extend({ tableName: 'users', tasks: function() { return this.hasMany(Task); } }); module.exports = User; ``` `User`模型包含`hasMany()`函數。 `model/task.js` ```js const knex = require('../config/db').knex; const bookshelf = require('bookshelf')(knex); const Task = bookshelf.Model.extend({ tableName: 'tasks', }); module.exports = Task; ``` 這是`Task`模型。 `has_many.js` ```js const knex = require('./config/db').knex; const User = require('./model/user'); async function doQuery() { try { let val = await User.where({ id: 1 }).fetch({ withRelated: ['tasks'], require: true }); console.log(val.toJSON()); } catch (e) { console.log(`Failed to fetch data: ${e}`); } finally { knex.destroy(); } } doQuery(); ``` 在示例中,我們獲取用戶及其任務。 ```js $ node has_many.js { id: 1, name: 'John Doe', tasks: [ { id: 1, user_id: 1, name: 'Task A' }, { id: 2, user_id: 1, name: 'Task B' }, { id: 3, user_id: 1, name: 'Task C' } ] } ``` ID 為 1 的用戶具有三個任務。 ### Bookshelf.js `belongsTo()`一對多 在一對多的情況下,`belongsTo()`是`hasMany()`的倒數,并且是關聯的一側。 `model/user.js` ```js const knex = require('../config/db').knex; const bookshelf = require('bookshelf')(knex); const User = bookshelf.Model.extend({ tableName: 'users', }); module.exports = User; ``` 這是`User`模型。 `model/task.js` ```js const knex = require('../config/db').knex; const bookshelf = require('bookshelf')(knex); const User = require('./user'); const Task = bookshelf.Model.extend({ tableName: 'tasks', user: function() { return this.belongsTo(User); } }); module.exports = Task; ``` `Task`模型包含`belongsTo()`函數。 `belongs_to2.js` ```js const knex = require('./config/db').knex; const Task = require('./model/task'); async function doQuery() { try { let val = await Task.where({ id: 4 }).fetch({ withRelated: ['user'], require: true }); console.log(val.toJSON()); } catch (e) { console.log(`Failed to fetch data: ${e}`); } finally { knex.destroy(); } } doQuery(); ``` 在示例中,我們與任務的關聯用戶一起獲取任務。 在本教程中,我們使用書架庫。 我們創建了一些與 PostgreSQL 交互的命令行程序。 您可能也對以下相關教程感興趣: [Sequelize 教程](/javascript/sequelize/), [Node Postgres 教程](/javascript/nodepostgres/)或 [JavaScript 教程](/all/#js)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看