Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: misleading aliases in multiple associations docs #280

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 43 additions & 4 deletions docs/core-concepts/assocs.md
Original file line number Diff line number Diff line change
Expand Up @@ -680,16 +680,55 @@ Practical demonstration:
await Bar.findOne({ include: Foo });
```

## Multiple associations involving the same models
## Multiple associations between the same models

In Sequelize, it is possible to define multiple associations between the same models. You just have to define different aliases for them:

```js
Team.hasOne(Game, { as: 'HomeTeam', foreignKey: 'homeTeamId' });
Team.hasOne(Game, { as: 'AwayTeam', foreignKey: 'awayTeamId' });
```typescript
const Team = sequelize.define('team', {
name: DataTypes.TEXT,
}, { timestamps: true });
const Game = sequelize.define('game', {
name: DataTypes.TEXT,
}, { timestamps: true });

Team.hasOne(Game, { as: 'HomeGame', foreignKey: 'homeGameId' });
Team.hasOne(Game, { as: 'AwayGame', foreignKey: 'awayGameId' });
Game.belongsTo(Team);
```

Now you able to use the associations with Lazy Loading:

```typescript
// Find the home team name
const awesomeHomeTeam = await Team.findOne({
where: {
name: "Home Ball Team"
},
});

// Find the home team game
const selectedHomeTeamGame = await awesomeHomeTeam.getHomeGame();

console.log('Team Name:', awesomeHomeTeam.name); // Home Ball Team
console.log('Team Game Name:', selectedHomeTeamGame.name); // Home Ball Game
```

or with Eager Loading:

```typescript
// Find the home team name
const awesomeHomeTeam = await Team.findOne({
where: {
name: "Home Ball Team"
},
include: Game, // Add `include` option to use eager loading
});

console.log('Team Name:', awesomeHomeTeam.name); // Home Ball Team
console.log('Team Game Name:', awesomeHomeTeam.game.name); // Home Ball Game
```

## Creating associations referencing a field which is not the primary key

In all the examples above, the associations were defined by referencing the primary keys of the involved models (in our case, their IDs). However, Sequelize allows you to define an association that uses another field, instead of the primary key field, to establish the association.
Expand Down