Reputation: 175
How i can update value in database using objection ? My SQL query works perfect.
UPDATE "freePlace"
SET number = number-1
WHERE date >= '2017-10-20' AND date <= '2017-10-30' AND "idObject" = '1'
My objection code:
FreePlace.query().patch({number:number+1}).where('date', '>=', startDate)
.andWhere('date', '<=', endDate)
.andWhere('idParking', '=', parkingId)
Problem is in patch({number:number+1}) how i need do this ?
Upvotes: 4
Views: 2880
Reputation: 250
You can use the increment
/decrement
methods:
FreePlace.query()
.increment('number', 1)
.where('date', '>=', startDate)
.andWhere('date', '<=', endDate)
.andWhere('idParking', '=', parkingId)
If you need to update something else in the same query, you can use raw
FreePlace.query()
.patch({
number: raw('number + 1'),
somethingElse: 42
})
.where('date', '>=', startDate)
.andWhere('date', '<=', endDate)
.andWhere('idParking', '=', parkingId)
raw
comes from const { raw } = require('objection')
Upvotes: 10
Reputation: 7355
Looks like you need to use ref(). The code as you have it won't know where to get the value of "number+1".
How about this?
FreePlace.query().patch({number:ref('number')+1})
.where('date', '>=', startDate)
.andWhere('date', '<=', endDate)
.andWhere('idParking', '=', parkingId)
See this example from objection.js docs:
Person
.query()
.patch({
age: Person.query().avg('age'),
firstName: Person.raw("'Jenni' || 'fer'"),
oldLastName: ref('lastName')
});
Upvotes: 4