Skip to content

Commit c95f343

Browse files
authored
document composite PK support in findByPk (#788)
1 parent ba3c7a2 commit c95f343

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

docs/querying/select-methods.md

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -63,16 +63,26 @@ const project = await Project.findOne({
6363

6464
The [`findByPk`](pathname:///api/v7/classes/_sequelize_core.index.Model.html#findByPk) method obtains only a single entry from the table, using the provided primary key.
6565

66-
```js
67-
const project = await Project.findByPk(123);
68-
if (project === null) {
69-
console.log('Not found!');
70-
} else {
71-
console.log(project instanceof Project); // true
72-
// Its primary key is 123
73-
}
66+
```ts
67+
const project: Project | null = await Project.findByPk(123);
68+
```
69+
70+
If your model has a [composite primary key](../models/defining-models.mdx#composite-primary-keys), you can pass an object with the primary key values:
71+
72+
```ts
73+
const projectMember: ProjectMember | null = await ProjectMember.findByPk({
74+
projectId: 123,
75+
userId: 456,
76+
});
7477
```
7578

79+
:::warning TypeScript
80+
81+
We do not currently have a way to determine which columns are primary keys in TypeScript.
82+
This means that only runtime checks will ensure that the primary key is passed correctly.
83+
84+
:::
85+
7686
## `findAndCountAll`
7787

7888
The [`findAndCountAll`](pathname:///api/v7/classes/_sequelize_core.index.Model.html#findAndCountAll) method is a convenience method that combines `findAll` and `count`. This is useful when dealing with queries related to pagination where you want to retrieve data with a `limit` and `offset` but also need to know the total number of records that match the query.

0 commit comments

Comments
 (0)