haltcase / trilogy

TypeScript SQLite layer with support for both native C++ & pure JavaScript drivers.
https://trilogy.js.org
MIT License
264 stars 24 forks source link

[question] how to perform WHERE and AND clauses using find method ? #54

Closed kmsheng closed 7 years ago

kmsheng commented 7 years ago

https://trilogy.js.org/#/api?id=find

Array syntax is either a key / value pair (equal to) or a length of 3,
 ie. ['age', '<', 65] (allows other comparisons)

For example, if I want to select where age is less than 65 and sex is male

haltcase commented 7 years ago

Multiple clauses isn't really covered in the current API but I'd definitely like to add it now that you mention it. Initial reaction is to have a new method for it, to avoid ambiguity and too much overload of find's signature... something like:

model.findWhere([column], [...criteria], [options])

where criteria is an Array of the Arrays / Objects that find accepts.

people.findWhere([
  ['age', '<', 65],
  { sex: 'male' }
]).then(found => {})

Thoughts on the method name are welcome.

kmsheng commented 7 years ago

I have no preference for the method name, but the query builder should be chainable. Most of the ORMs I know they do something like:

people.findWhere(['age', '<', 65])
  .andWhere({sex: 'male'})
  .orWhere({career: 'engineer'});

https://forum.phalconphp.com/discussion/12155/querybuilder-orwhere-inside-andwhere http://knexjs.org/#Raw-Bindings

haltcase commented 7 years ago

I specifically built trilogy so that it would not have a chainable API. If you want to use a chainable API you can use db.raw() with knex queries, which is easy enough, or just use knex by itself.

kmsheng commented 7 years ago

Ok. No problem.

haltcase commented 7 years ago

This is possible in v1.2.0 ( without a new method ) anywhere that accepts criteria:

people.find([
  ['age', '<', 65],
  { sex: 'male' }
]).then(found => {})

It's just an Array of any number of the other forms of where clause. This covers and where - things like or and combinations of logical chains I think I'll leave to db.raw() and knex queries.

Thanks for filing!