@@ -23,7 +23,7 @@ Requires `sequelize@^4.0.0`. Once v5 is released I'll check if it's still
23
23
compatible. Not making any effort to support versions < 4, but you're welcome
24
24
to make a PR.
25
25
26
- ## Example
26
+ ## Examples
27
27
28
28
``` js
29
29
const Sequelize = require (' sequelize' )
@@ -44,3 +44,40 @@ WHERE ${User.attributes.birthday} = ${new Date('2346-7-11')} AND
44
44
${ Sequelize .literal (lock ? ' FOR UPDATE' : ' ' )} ` ).then (console .log );
45
45
// => [ [ { name: 'Jimbob' } ], Statement { sql: 'SELECT "name" FROM "Users" WHERE "birthday" = $1 AND "active" = $2 FOR UPDATE' } ]
46
46
```
47
+
48
+ Sometimes custom subqueries within a Sequelize ` where ` clause can be useful.
49
+ In this case, there is no way to use query parameters. You can use
50
+ ` sql.escape ` in this context to inline the escaped values rather than using
51
+ query parameters:
52
+
53
+ ``` js
54
+ const {Op } = Sequelize
55
+
56
+ const User = sequelize .define (' User' , {
57
+ name: {type: Sequelize .STRING },
58
+ })
59
+ const Organization = sequelize .define (' Organization' , {
60
+ name: {type: Sequelize .STRING },
61
+ })
62
+ const OrganizationMember = sequelize .define (' OrganizationMember' , {
63
+ userId: {type: Sequelize .INTEGER },
64
+ organizationId: {type: Sequelize .INTEGER },
65
+ })
66
+ User .belongsToMany (Organization, {through: OrganizationMember})
67
+ Organization .belongsToMany (User, {through: OrganizationMember})
68
+
69
+ async function getUsersInOrganization (organizationId , where = {}) {
70
+ return await User .findAll ({
71
+ where: {
72
+ ... where,
73
+ // Using a sequelize include clause to do this kind of sucks tbh
74
+ id: {[Op .in ]: Sequelize .literal (sql .escape `
75
+ SELECT ${ OrganizationMember .attributes .userId }
76
+ FROM ${ OrganizationMember}
77
+ WHERE ${ OrganizationMember .attributes .organizationId } = ${ organizationId}
78
+ ` )}
79
+ // SELECT "userId" FROM "OrganizationMembers" WHERE "organizationId" = 2
80
+ },
81
+ })
82
+ }
83
+ ```
0 commit comments