Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

sequelize association alias

const User = sequelize.define('user', {/* ... */})
const Project = sequelize.define('project', {/* ... */})

// One-way associations
Project.hasOne(User)

/*
  In this example hasOne will add an attribute projectId to the User model!
  Furthermore, Project.prototype will gain the methods getUser and setUser according
  to the first parameter passed to define. If you have underscore style
  enabled, the added attribute will be project_id instead of projectId.

  The foreign key will be placed on the users table.

  You can also define the foreign key, e.g. if you already have an existing
  database and want to work on it:
*/

Project.hasOne(User, { foreignKey: 'initiator_id' })

/*
  Because Sequelize will use the model's name (first parameter of define) for
  the accessor methods, it is also possible to pass a special option to hasOne:
*/

Project.hasOne(User, { as: 'Initiator' })
// Now you will get Project.getInitiator and Project.setInitiator

// Or let's define some self references
const Person = sequelize.define('person', { /* ... */})

Person.hasOne(Person, {as: 'Father'})
// this will add the attribute FatherId to Person

// also possible:
Person.hasOne(Person, {as: 'Father', foreignKey: 'DadId'})
// this will add the attribute DadId to Person

// In both cases you will be able to do:
Person.setFather
Person.getFather

// If you need to join a table twice you can double join the same table
Team.hasOne(Game, {as: 'HomeTeam', foreignKey : 'homeTeamId'});
Team.hasOne(Game, {as: 'AwayTeam', foreignKey : 'awayTeamId'});

Game.belongsTo(Team);
Comment

PREVIOUS NEXT
Code Example
Javascript :: add icon to angular 
Javascript :: Math max with array js 
Javascript :: React social login button 
Javascript :: bresenham algorithm 
Javascript :: split() javascript 
Javascript :: v-bind shorthand 
Javascript :: hooks developed by react native 
Javascript :: state in react 
Javascript :: random color generator 
Javascript :: js contenteditable button spacebar 
Javascript :: Sorting Data Accessor 
Javascript :: ready function jq 
Javascript :: round down javascript 
Javascript :: how javascript interpreter works 
Javascript :: what does useref do react 
Javascript :: append item in treeview vuetify 
Javascript :: vue dispatch action at tab close 
Javascript :: for of loop ecmascript 6 
Javascript :: header react native 
Javascript :: .reduce javascript 
Javascript :: post request enabled in express js 
Javascript :: sequelize order by nulls last 
Javascript :: react native floating action button 
Javascript :: mongodb populate 
Javascript :: Highest and Lowest 
Javascript :: Get position of each element using jquery 
Javascript :: repeat network call n times in js 
Javascript :: react set state before render 
Javascript :: execcommand image 
Javascript :: mern heroku Error: ENOENT: no such file or directory 
ADD CONTENT
Topic
Content
Source link
Name
4+4 =