Skip to content
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
64 changes: 64 additions & 0 deletions src/guide/raw.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,70 @@ query will become:
select * from users where id in (?, ?, ?) /* with bindings [1,2,3] */
```

For raw queries that involve combining multiple named bindings where one of the bindings is a string array, you'll need to turn the string array in to a string and let knex build a query.

```js
const names = ['Sally', 'Jay', 'Foobar'];
const bindings = {
names: knex.raw(
`'${names.join("','")}'`
) /* generates 'Sally','Jay','Foobar' */,
age: 21,
limit: 100,
};
```

Pass the bindings to your raw query:

```js
knex.raw(
`
select * from people
where "name" in (:names)
and "age" > :age
limit :limit
`,
bindings
);
```

query will become:

```sql
select * from people
where "name" in ('Sally', 'Jay', 'Foobar')
and "age" > 21
limit 100
```

You can also use `ANY`, which in many cases is equivalent to `WHERE IN`.
```js
const names = ['Sally', 'Jay', 'Foobar'];
const bindings = {
names,
age: 21,
limit: 100,
};
knex.raw(
`
select * from people
where "name" = any(:names)
and "age" > :age
limit :limit
`,
bindings
);
```

This evaluates to:

```sql
select * from people
where "name" = any('{"Sally", "Jay", "Foobar"}')
and "age" > 21
limit 100
```

To prevent replacement of `?` one can use the escape sequence `\\?`.

```js
Expand Down