Leoric is an object-relational mapping library for Node.js, with which you can manipulate database like this:
const { Bone, connect } = require('leoric')
// define model
class Post extends Bone {
static initialize() {
this.belongsTo('author', { Model: 'User' })
this.hasMany('comments')
}
}
async function() {
// connect models to database
await connect({
client: 'mysql',
host: 'example.com', /* among other connection options */
models: [Post]
})
// CRUD
await Post.create({ title: 'New Post' })
const post = await Post.findOne({ title: 'New Post' })
post.title = 'Untitled'
await post.save()
// or UPDATE directly
await Post.update({ title: 'Untitled' }, { title: 'New Post' })
// find with associations
await Post.include('comments').where('posts.title = ?', 'New Post')
// => Post { id: 1, title: 'New Post', ...,
// comments: [ Comment { id, content }, ... ] }
}
本站点提供中文版本,猛戳左边了解更多。
Leoric can be used in many web frameworkds from Node.js community. If you are developing with Egg framework, it is highly recommended using the egg-orm plugin:
/* config/plugin.js */
exports.orm = {
enable: true,
package: 'egg-orm',
};
/* config/config.default.js */
exports.orm = {
client: 'mysql',
database: 'temp',
host: 'localhost',
models: 'app/model',
};
The models defined in app/model
will be accessible from ctx.model
, such as ctx.model.User
:
// app/controller/home.js
const { Controller } = require('egg');
module.exports = class HomeController extends Controller {
async index() {
const users = await ctx.model.User.find({
corpId: ctx.model.Corp.findOne({ name: 'alipay' }),
});
ctx.body = users;
}
};
JavaScript | SQL |
---|---|
For detailed informations, please check out following guides accordingly:
There are many ways in which you can participate in the project, for example:
If you are interested in fixing issues and contributing directly to the code base, please see the document How to Contribute, which covers the following:
If developing web applications with Egg framework, it’s highly recommended using the egg-orm plugin. More detailed examples about setting up egg-orm with egg framework in either JavaScript or TypeScript can be found at https://github.com/eggjs/egg-orm/tree/master/examples
If developing web applications (or serverless functions) with Midway, the corresponding component called @midwayjs/leoric is what you need. Please refer to the linked documentation for starter, or the repo directory for more examples.