Sequelize: bulk insert with HasMany association gives incorrect result

Viewed 238

Say I have a basic HasMany association of teams and players. I have this raw data in csv:

csv raw data
+-----------------------+-----------------+
|        player         |      team       |
+-----------------------+-----------------+
| Thibaut Courtois      | Real Madrid CF  |
| Dani Carvajal         | Real Madrid CF  |
| Marc-André ter Stegen | FC Barcelona    |
| Sergiño Dest          | FC Barcelona    |
| Benjamin Lecomte      | Atlético Madrid |
| José María Giménez    | Atlético Madrid |
+-----------------------+-----------------+

Now I want to insert this data into two tables: teams and players, so that the final result will be:

teams
+----+-----------------+
| id |      name       |
+----+-----------------+
|  1 | Real Madrid CF  |
|  2 | FC Barcelona    |
|  3 | Atlético Madrid |
+----+-----------------+
players
+----+-----------------------+--------+
| id |         name          | TeamId |
+----+-----------------------+--------+
|  1 | Thibaut Courtois      |      1 |
|  2 | Dani Carvajal         |      1 |
|  3 | Marc-André ter Stegen |      2 |
|  4 | Sergiño Dest          |      2 |
|  5 | Benjamin Lecomte      |      3 |
|  6 | José María Giménez    |      3 |
+----+-----------------------+--------+

The code to create this schema is quite straightforward:

const Player = sequelize.define("Player", {
  name: DataTypes.STRING,
});

const Team = sequelize.define("Team", {
  name: {
    type: DataTypes.STRING,
    unique: true,
  },
});

Team.hasMany(Player);
Player.belongsTo(Team);

The problem now comes when I try to bulk insert the raw data:

const data = [
  { player: "Thibaut Courtois", team: "Real Madrid CF" },
  { player: "Dani Carvajal", team: "Real Madrid CF" },
  { player: "Marc-André ter Stegen", team: "FC Barcelona" },
  { player: "Sergiño Dest", team: "FC Barcelona" },
  { player: "Benjamin Lecomte", team: "Atlético Madrid" },
  { player: "José María Giménez", team: "Atlético Madrid" },
];
const dataToCreate = data.map((d) => ({
  name: d.player,
  Team: { name: d.team },
}));
await Player.bulkCreate(dataToCreate, {
  include: [{ model: Team, ignoreDuplicates: true }],
});

After running the above code, the Team table gets filled correctly and is the exact same as shown above.

But I get weird results for the Player table:

+----+-----------------------+--------+
| id |         name          | TeamId |
+----+-----------------------+--------+
|  1 | Thibaut Courtois      | 1      |
|  2 | Dani Carvajal         | 2      |
|  3 | Marc-André ter Stegen | 3      |
|  4 | Sergiño Dest          | null   |
|  5 | Benjamin Lecomte      | null   |
|  6 | José María Giménez    | null   |
+----+-----------------------+--------+

I am using sequelize v6.7.0 and mysql2 v2.3.0

0 Answers
Related