Skip to content

Instantly share code, notes, and snippets.

@helfer
Created April 22, 2016 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helfer/eb46a1ff9ee46cea5fac247b5f469e7c to your computer and use it in GitHub Desktop.
Save helfer/eb46a1ff9ee46cea5fac247b5f469e7c to your computer and use it in GitHub Desktop.
import Sequelize from 'sequelize';
import casual from 'casual';
import _ from 'lodash';
const db = new Sequelize('blog', null, null, {
dialect: 'sqlite',
storage: './blog.sqlite',
});
const AuthorModel = db.define('author', {
firstName: { type: Sequelize.STRING },
lastName: { type: Sequelize.STRING },
});
const PostModel = db.define('post', {
title: { type: Sequelize.STRING },
text: { type: Sequelize.STRING },
});
AuthorModel.hasMany(PostModel);
PostModel.belongsTo(AuthorModel);
// create mock data with a seed, so we always get the same
casual.seed(123);
db.sync({ force: true }).then(() => {
_.times(10, () => {
return AuthorModel.create({
firstName: casual.first_name,
lastName: casual.last_name,
}).then((author) => {
return author.createPost({
title: `A post by ${author.firstName}`,
text: casual.sentences(3),
});
});
});
});
const Author = db.models.author;
const Post = db.models.post;
export { Author, Post };
@nogtini
Copy link

nogtini commented May 24, 2016

Do you know where the .createPost method from line 31 is defined? I could understand a .create method, but .createPost seems oddly specific.

@sbussard
Copy link

sbussard commented Nov 7, 2016

@yejodido I would also like to know the answer for that. I know that createPost is dynamically generated by sequelize, but I don't know what the generic equivalent is

@itshallrun
Copy link

would also like to know

@Taslack
Copy link

Taslack commented Mar 24, 2017

so createPost comes from the AuthorModel.hasMany(PostModel);. Here is the documentation: http://docs.sequelizejs.com/en/latest/api/associations/belongs-to/

Sequelize autocamelcases post from db.define('post'.... which createPost is a reference too. Be aware of plural and non-plural when using sequelize, because it does make a difference on how you data is added/removed from the database.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment