orm框架的使用
Install
Node.js Version Support
Supported: 0.12 - 6.0 +
Tests are run on Travis CI If you want you can run tests locally:
DBMS Support
- MySQL & MariaDB
- PostgreSQL
- Amazon Redshift
- SQLite
- MongoDB (beta, missing aggregation for now)
Features
- Create Models, sync, drop, bulk create, get, find, remove, count, aggregated functions
- Create Model associations, find, check, create and remove
- Define custom validations (several builtin validations, check instance properties before saving - see enforce for details)
- Model instance caching and integrity (table rows fetched twice are the same object, changes to one change all)
- Plugins: MySQL FTS , Pagination , Transaction, Timestamps, Migrations
Introduction
This is a node.js object relational mapping module.
An example:
Promises
You can use the promise enabled wrapper library.
Express
If you're using Express, you might want to use the simple middleware to integrate more easily.
You can call orm.express more than once to have multiple database connections. Models defined across connections will be joined together in req.models. Don't forget to use it before app.use(app.router), preferably right after your assets public folder(s).
Examples
See examples/anontxt for an example express based app.
Documentation
Documentation is moving to the wiki.
Settings
See information in the wiki.
Connecting
See information in the wiki.
Models
A Model is an abstraction over one or more database tables. Models support associations (more below). The name of the model is assumed to match the table name.
Models support behaviours for accessing and manipulating table data.
Defining Models
See information in the wiki.
Properties
See information in the wiki.
Instance Methods
Are passed in during model definition.
Model Methods
Are defined directly on the model.
Loading Models
Models can be in separate modules. Simply ensure that the module holding the models uses module.exports to publish a function that accepts the database connection, then load your models however you like.
Note - using this technique you can have cascading loads.
Synchronizing Models
See information in the wiki.
Dropping Models
See information in the wiki.
Advanced Options
ORM2 allows you some advanced tweaks on your Model definitions. You can configure these via settings or in the call to define when you setup the Model.
For example, each Model instance has a unique ID in the database. This table column is added automatically, and called "id" by default.
If you define your own key: true column, "id" will not be added:
Pet model will have 2 columns, an UID and a name.
It's also possible to have composite keys:
Other options:
identityCache: (default:false) Set it totrueto enable identity cache (Singletons) or set a timeout value (in seconds);autoSave: (default:false) Set it totrueto save an Instance right after changing any property;autoFetch: (default:false) Set it totrueto fetch associations when fetching an instance from the database;autoFetchLimit: (default:1) IfautoFetchis enabled this defines how many hoops (associations of associations) you want it to automatically fetch.
Hooks
See information in the wiki.
Finding Items
Model.get(id, [ options ], cb)
To get a specific element from the database use Model.get.
Model.find([ conditions ] [, options ] [, limit ] [, order ] [, cb ])
Finding one or more elements has more options, each one can be given in no specific parameter order. Only options has to be after conditions (even if it's an empty object).
If you need to sort the results because you're limiting or just because you want them sorted do:
There are more options that you can pass to find something. These options are passed in a second object:
You can also use raw SQL when searching. It's documented in the Chaining section below.
Model.count([ conditions, ] cb)
If you just want to count the number of items that match a condition you can just use .count()instead of finding all of them and counting. This will actually tell the database server to do a count (it won't be done in the node process itself).
Model.exists([ conditions, ] cb)
Similar to .count(), this method just checks if the count is greater than zero or not.
Aggregating Functions
If you need to get some aggregated values from a Model, you can use Model.aggregate(). Here's an example to better illustrate:
An Array of properties can be passed to select only a few properties. An Object is also accepted to define conditions.
Here's an example to illustrate how to use .groupBy():
Base .aggregate() methods
.limit(): you can pass a number as a limit, or two numbers as offset and limit respectively.order(): same asModel.find().order()
Additional .aggregate() methods
minmaxavgsumcount(there's a shortcut to this -Model.count)
There are more aggregate functions depending on the driver (Math functions for example).
Chaining
If you prefer less complicated syntax you can chain .find() by not giving a callback parameter.
If you want to skip just one or two properties, you can call .omit() instead of .only.
Chaining allows for more complicated queries. For example, we can search by specifying custom SQL:
It's bad practice to manually escape SQL parameters as it's error prone and exposes your application to SQL injection. The ? syntax takes care of escaping for you, by safely substituting the question mark in the query with the parameters provided. You can also chain multiple where clauses as needed.
.find, .where & .all do the same thing; they are all interchangeable and chainable.
You can also order or orderRaw:
You can also chain and just get the count in the end. In this case, offset, limit and order are ignored.
Also available is the option to remove the selected items. Note that a chained remove will not run any hooks.
You can also make modifications to your instances using common Array traversal methods and save everything in the end.
Of course you could do this directly on .find(), but for some more complicated tasks this can be very usefull.
Model.find() does not return an Array so you can't just chain directly. To start chaining you have to call .each() (with an optional callback if you want to traverse the list). You can then use the common functions .filter(), .sort() and .forEach() more than once.
In the end (or during the process..) you can call:
.count()if you just want to know how many items there are;.get()to retrieve the list;.save()to save all item changes.
Conditions
Conditions are defined as an object where every key is a property (table column). All keys are supposed to be concatenated by the logical AND. Values are considered to match exactly, unless you're passing an Array. In this case it is considered a list to compare the property with.
If you need other comparisons, you have to use a special object created by some helper functions. Here are a few examples to describe it:
Raw queries
Identity pattern
You can use the identity pattern (turned off by default). If enabled, multiple different queries will result in the same result - you will get the same object. If you have other systems that can change your database or you need to call some manual SQL queries, you shouldn't use this feature. It is also know to cause some problems with complex autofetch relationships. Use at your own risk.
It can be enabled/disabled per model:
and also globally:
The identity cache can be configured to expire after a period of time by passing in a number instead of a boolean. The number will be considered the cache timeout in seconds (you can use floating point).
Note: One exception about Caching is that it won't be used if an instance is not saved. For example, if you fetch a Person and then change it, while it doesn't get saved it won't be passed from Cache.
Creating Items
Model.create(items, cb)
To insert new elements to the database use Model.create.
Updating Items
Every item returned has the properties that were defined to the Model and also a couple of methods you can use to change each item.
Updating and then saving an instance can be done in a single call:
If you want to remove an instance, just do:
Validations
See information in the wiki.
Associations
An association is a relation between one or more tables.
hasOne
Is a many to one relationship. It's the same as belongs to.
Eg: Animal.hasOne('owner', Person).
Animal can only have one owner, but Person can have many animals.
Animal will have the owner_id property automatically added.
The following functions will become available:
Chain Find
The hasOne association is also chain find compatible. Using the example above, we can do this to access a new instance of a ChainFind object:
Reverse access
will add the following:
hasMany
Is a many to many relationship (includes join table).
Eg: Patient.hasMany('doctors', Doctor, { why: String }, { reverse: 'patients', key: true }).
Patient can have many different doctors. Each doctor can have many different patients.
This will create a join table patient_doctors when you call Patient.sync():
| column name | type |
|---|---|
| patient_id | Integer (composite key) |
| doctor_id | Integer (composite key) |
| why | varchar(255) |
The following functions will be available:
To associate a doctor to a patient:
which will add {patient_id: 4, doctor_id: 6, why: "remove appendix"} to the join table.
getAccessor
This accessor in this type of association returns a ChainFind if not passing a callback. This means you can do things like:
extendsTo
If you want to split maybe optional properties into different tables or collections. Every extension will be in a new table, where the unique identifier of each row is the main model instance id. For example:
This will create a table person with columns id and name. The extension will create a table person_address with columns person_id, street and number. The methods available in the Person model are similar to an hasOne association. In this example you would be able to call .getAddress(cb), .setAddress(Address, cb), ..
Note: you don't have to save the result from Person.extendsTo. It returns an extended model. You can use it to query directly this extended table (and even find the related model) but that's up to you. If you only want to access it using the original model you can just discard the return.
Examples & options
If you have a relation of 1 to n, you should use hasOne (belongs to) association.
You can mark the owner_id field as required in the database by specifying the required option:
If a field is not required, but should be validated even if it is not present, then specify the alwaysValidate option. (this can happen, for example when validation of a null field depends on other fields in the record)
If you prefer to use another name for the field (owner_id) you can change this parameter in the settings.
Note: This has to be done before the association is specified.
The hasMany associations can have additional properties in the association table.
If you prefer you can activate autoFetch. This way associations are automatically fetched when you get or find instances of a model.
You can also define this option globally instead of a per association basis.
Associations can make calls to the associated Model by using the reverse option. For example, if you have an association from ModelA to ModelB, you can create an accessor in ModelB to get instances from ModelA. Confusing? Look at the next example.
This makes even more sense when having hasMany associations since you can manage the many to many associations from both sides.
Adding external database adapters
To add an external database adapter to orm, call the addAdapter method, passing in the alias to use for connecting with this adapter, along with the constructor for the adapter:
See the documentation for creating adapters for more details.
orm框架的使用的更多相关文章
- ASP.NET MVC 使用 Petapoco 微型ORM框架+NpgSql驱动连接 PostgreSQL数据库
前段时间在园子里看到了小蝶惊鸿 发布的有关绿色版的Linux.NET——“Jws.Mono”.由于我对.Net程序跑在Linux上非常感兴趣,自己也看了一些有关mono的资料,但是一直没有时间抽出时间 ...
- 最好的5个Android ORM框架
在开发Android应用时,保存数据有这么几个方式, 一个是本地保存,一个是放在后台(提供API接口),还有一个是放在开放云服务上(如 SyncAdapter 会是一个不错的选择). 对于第一种方式, ...
- [Android]Android端ORM框架——RapidORM(v2.1)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/6020412.html [Android]Android端ORM ...
- [Android]Android端ORM框架——RapidORM(v2.0)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5626716.html [Android]Android端ORM ...
- 轻量级ORM框架——第一篇:Dapper快速学习
我们都知道ORM全称叫做Object Relationship Mapper,也就是可以用object来map我们的db,而且市面上的orm框架有很多,其中有一个框架 叫做dapper,而且被称为th ...
- ORM之殇,我们需要什么样的ORM框架?
最近在研究ORM,究竟什么样的框架才是我们想要的 开发框架的意义在于 开发更标准,更统一,不会因为不同人写的代码不一样 开发效率更高,无需重新造轮子,重复无用的代码,同时简化开发流程 运行效率得到控制 ...
- 轻量级ORM框架初探-Dapper与PetaPoco的基本使用
一.EntityFramework EF是传统的ORM框架,也是一个比较重量级的ORM框架.这里仍然使用EF的原因在于为了突出轻量级ORM框架的性能,所谓有对比才有更优的选择. 1.1 准备一张数据库 ...
- ORM框架示例及查询测试,上首页修改版(11种框架)
继上次ORM之殇,我们需要什么样的ORM框架? 整理了11个ORM框架测试示例,通过示例代码和结果,能很容易了解各种框架的特性,优缺点,排名不分先后 EF PDF XCODE CRL NHiberna ...
- [Android]Android端ORM框架——RapidORM(v1.0)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/4748077.html Android上主流的ORM框架有很多 ...
- 吉特仓库管理系统-ORM框架的使用
最近在园子里面连续看到几篇关于ORM的文章,其中有两个印象比较深刻<<SqliteSugar>>,另外一篇文章是<<我的开发框架之ORM框架>>, 第一 ...
随机推荐
- Redis 缓存穿透,缓存击穿,缓存雪崩的解决方案分析
设计一个缓存系统,不得不要考虑的问题就是:缓存穿透.缓存击穿与失效时的雪崩效应. 一.什么样的数据适合缓存? 分析一个数据是否适合缓存,我们要从访问频率.读写比例.数据一致性等要求去分析. 二.什么 ...
- python 的 ord()、 chr()、 unichr() 函数
一. ord() 函数描述ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返 ...
- Python开发【Tornado】:异步Web服务(一)
异步Web服务 前言: 到目前为止,我们已经看到了许多使Tornado成为一个Web应用强有力框架的功能.它的简单性.易用性和便捷性使其有足够的理由成为许多Web项目的不错的选择.然而,Tornado ...
- 由SOAP说开去 - - 谈谈WebServices、RMI、RPC、SOA、REST、XML、JSON
引子: 关于SOAP其实我一直模模糊糊不太理解,这种模模糊糊的感觉表述起来是这样: 在使用web服务时(功能接口),本来我就可以通过安卓中固有的http类(使用http协议),来发送http请求,并且 ...
- mysql float 浮点型
定点数类型 DEC等同于DECIMAL 浮点类型:FLOAT DOUBLE 作用:存储薪资.身高.体重.体质参数等 m,d 都是设置宽度 =============================== ...
- 用nginx的反向代理机制解决前端跨域问题在nginx上部署web静态页面
用nginx的反向代理机制解决前端跨域问题在nginx上部署web静态页面 1.什么是跨域以及产生原因 跨域是指a页面想获取b页面资源,如果a.b页面的协议.域名.端口.子域名不同,或是a页面为ip地 ...
- SaltStack系列(一)之环境部署、命令及配置文件详解
一.SaltStack介绍 1.1 saltstack简介: saltstack是基于python开发的一套C/S架构配置管理工具,它的底层使用ZeroMQ消息队列pub/sub方式通信,使用SSL证 ...
- 记一次mysql启动不了的问题
在linux上用的是xampp,mysql启动没有报任何错误,但就是查找不到进程,于是找mysql错误日志,日志在哪?在lampp/var/mysql 以.err结尾的文件里.里面内容如下; /opt ...
- (13)如何使用Cocos2d-x 3.0制作基于tilemap的游戏:第一部分
引言 程序截图: 本教程将会教大家如何使用Cocos2d-x来做一个基于tile地图的游戏,当然还有Tiled地图编辑器.(我们小时候玩的小霸王小学机里面的游戏,大部分都是基于tile地图的游戏,如坦 ...
- Java面试:投行的15个多线程和并发面试题
多线程和并发问题已成为各种 Java 面试中必不可少的一部分.如果你准备参加投行的 Java 开发岗位面试,比如巴克莱银行(Barclays).花旗银行(Citibank).摩根史坦利投资公司(Mor ...