associations.test.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. const chai = require('chai');
  3. const expect = chai.expect;
  4. const Support = require('../../support');
  5. const dialect = Support.getTestDialect();
  6. const { DataTypes } = require('@sequelize/core');
  7. if (dialect === 'mariadb') {
  8. describe('[MariaDB Specific] Associations', () => {
  9. describe('many-to-many', () => {
  10. describe('where tables have the same prefix', () => {
  11. it('should create a table wp_table1wp_table2s', async function () {
  12. const Table2 = this.sequelize.define('wp_table2', { foo: DataTypes.STRING });
  13. const Table1 = this.sequelize.define('wp_table1', { foo: DataTypes.STRING });
  14. Table1.belongsToMany(Table2, { through: 'wp_table1swp_table2s' });
  15. Table2.belongsToMany(Table1, { through: 'wp_table1swp_table2s' });
  16. await Table1.sync({ force: true });
  17. await Table2.sync({ force: true });
  18. expect(this.sequelize.models.get('wp_table1swp_table2s')).to.exist;
  19. });
  20. });
  21. describe('when join table name is specified', () => {
  22. beforeEach(async function () {
  23. const Table2 = this.sequelize.define('ms_table1', { foo: DataTypes.STRING });
  24. const Table1 = this.sequelize.define('ms_table2', { foo: DataTypes.STRING });
  25. Table1.belongsToMany(Table2, { through: 'table1_to_table2' });
  26. Table2.belongsToMany(Table1, { through: 'table1_to_table2' });
  27. await Table1.sync({ force: true });
  28. await Table2.sync({ force: true });
  29. });
  30. it('should not use only a specified name', function () {
  31. expect(this.sequelize.models.get('ms_table1sms_table2s')).not.to.exist;
  32. expect(this.sequelize.models.get('table1_to_table2')).to.exist;
  33. });
  34. });
  35. });
  36. describe('HasMany', () => {
  37. beforeEach(async function () {
  38. // prevent periods from occurring in the table name since they are used to delimit (table.column)
  39. this.User = this.sequelize.define(`User${Math.ceil(Math.random() * 10_000_000)}`, {
  40. name: DataTypes.STRING,
  41. });
  42. this.Task = this.sequelize.define(`Task${Math.ceil(Math.random() * 10_000_000)}`, {
  43. name: DataTypes.STRING,
  44. });
  45. this.users = null;
  46. this.tasks = null;
  47. this.User.belongsToMany(this.Task, { as: 'Tasks', through: 'UserTasks' });
  48. this.Task.belongsToMany(this.User, { as: 'Users', through: 'UserTasks' });
  49. const users = [];
  50. const tasks = [];
  51. for (let i = 0; i < 5; ++i) {
  52. users[i] = { name: `User${Math.random()}` };
  53. tasks[i] = { name: `Task${Math.random()}` };
  54. }
  55. await this.sequelize.sync({ force: true });
  56. await this.User.bulkCreate(users);
  57. await this.Task.bulkCreate(tasks);
  58. });
  59. });
  60. });
  61. }