Guest User

Untitled

a guest
Jun 8th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. const Sequelize = require('sequelize');
  2. const config = require('./config')();
  3.  
  4. const {DataTypes} = Sequelize;
  5.  
  6. const db = new Sequelize({
  7. database: config.postgres.database,
  8. username: config.postgres.user,
  9. password: config.postgres.password,
  10. host: config.postgres.host,
  11. port: config.postgres.port,
  12. dialect: 'postgres',
  13. logging: false
  14. });
  15.  
  16. db.parents = db.define('Parent', {
  17. _id: {
  18. type: DataTypes.INTEGER,
  19. primaryKey: true,
  20. autoIncrement: true
  21. }
  22. }, {
  23. timestamps: false,
  24. tableName: 'parents'
  25. });
  26.  
  27. db.somethings = db.define('Something', {
  28. _id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}
  29. }, {
  30. timestamps: false,
  31. tableName: 'somethings'
  32. });
  33.  
  34. db.children = db.define('Child', {
  35. _id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
  36. parentId: DataTypes.INTEGER,
  37. somethingId: DataTypes.INTEGER
  38. }, {
  39. timestamps: false,
  40. tableName: 'children'
  41. });
  42.  
  43. db.parents.hasMany(db.children, {
  44. as: 'children',
  45. foreignKey: 'parentId'
  46. });
  47.  
  48. db.somethings.hasMany(db.children, {
  49. as: 'children',
  50. foreignKey: 'somethingId'
  51. });
  52.  
  53. db.children.belongsTo(db.parents, {
  54. as: 'parent',
  55. foreignKey: 'parentId',
  56. targetKey: '_id'
  57. });
  58.  
  59. db.children.belongsTo(db.somethings, {
  60. as: 'something',
  61. foreignKey: 'somethingId'
  62. });
  63.  
  64. (async () => {
  65. try {
  66. await db.transaction(async (transaction) => {
  67. await db.parents.truncate({transaction});
  68. await db.somethings.truncate({transaction});
  69. await db.children.truncate({transaction});
  70.  
  71. const {_id: parentId} = await db.parents.create({}, {transaction});
  72. const {_id: somethingId} = await db.somethings.create({}, {transaction});
  73.  
  74. await db.children.bulkCreate(
  75. [{parentId, somethingId}, {parentId, somethingId}],
  76. {transaction}
  77. );
  78.  
  79. const parents = await db.parents.findAll({
  80. include: [{
  81. model: db.children,
  82. as: 'children',
  83. required: true,
  84. include: [{
  85. model: db.somethings,
  86. as: 'something',
  87. required: true
  88. }]
  89. }],
  90. limit: 5,
  91. transaction,
  92. logging: console.log
  93. });
  94.  
  95. console.log(
  96. require('util').inspect(
  97. parents.map((parent) => parent.toJSON()),
  98. false,
  99. null
  100. )
  101. );
  102. });
  103. } catch (err) {
  104. console.log(err.stack);
  105. }
  106. })();
Add Comment
Please, Sign In to add comment