Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query with a list of id in Bookshelf JS

How can I get a list of records by PK in a single query using bookshelf.js?

The end query should be equivalent to:

SELECT * FROM `user` WHERE `id` IN (1,3,5,6,7);
like image 701
Vũ Nguyễn Avatar asked May 05 '16 03:05

Vũ Nguyễn


2 Answers

This solution works:

AdModel
  .where('search_id', 'IN', [1, 2, 3])
  .fetchAll();

You can also use the Knex QueryBuilder to get the same result

AdModel
.query(qb => {
    qb.whereIn('search_id',  [1, 2, 3]);
})
.fetchAll();
like image 172
Eric Ly Avatar answered Oct 21 '22 16:10

Eric Ly


List (single) query and fetching relations (withRelated)

BookshelfModel
  .where('field_id', 'IN', [1, 2, 3])
  .fetchAll({withRelated: ["tableA", "tableB"]});
like image 23
mbao01 Avatar answered Oct 21 '22 15:10

mbao01