Note that in this documentation, we borrow many examples and texts from Vuex ORM Next. We would like to credit Vuex ORM Next and the author of the section Kia King Ishii for the beautiful work.
This is a quick starting guide to begin using Pinia ORM. It assumes you have a basic understanding of Pinia. If you are not familiar with Pinia, please visit the Pinia Documentation to learn more.
To setup Pinia ORM, you must:
Don't worry. It's much easier than you think.
yarn add pinia-orm
import { createPinia } from 'pinia'import PiniaORM from 'pinia-orm'const pinia = createPinia().use(PiniaORM.install())
Models represent a schema of data that will be stored in Pinia. The schema often follows a servers API response, but it could also be whatever you like it to be.
Models may have relationships with other models. For example, a post could belong to a user, or a post has many comments.
The following examples will demonstrate what these models may look like:
User Model
// User Modelimport { Model } from 'pinia-orm'export default class User extends Model { // entity is a required property for all models. static entity = 'users' // List of all fields (schema) of the post model. `this.string()` declares // a string field type with a default value as the first argument. // `this.uid()` declares a unique id if none provided. static fields () { return { id: this.uid(), name: this.string(''), email: this.string('') } } // For typescript support of the field include also the next lines id!: string name!: string email!: string}
Post Model
// Post Modelimport { Model } from 'pinia-orm'import User from './User'export default class Post extends Model { static entity = 'posts' // `this.belongsTo(...)` declares this post belongs to a user. The first // argument is the `User` model class. The second is the field name for // the foreign key `userId`. static fields () { return { id: this.uid(), userId: this.attr(null), title: this.string(''), body: this.string(''), published: this.boolean(false), author: this.belongsTo(User, 'userId') } } id!: string userId!: string | null title!: string body!: string published!: boolean author!: User | null}
All models are declared by extending the Pinia ORM base Model class.
These examples create a User model and a Post model. The Post model has a belongsTo relationship to User defined by the author key. It's now possible to create posts that are associated with users.
You can learn more about models at Model: Getting Started.
Check out how to use Pinia ORM.