Record
A row of a PostgreSQL table returned by a model: change its fields and save, delete, reload, increment counters.
Records are the rows returned by model functions - create, find, findOne, findAll, findOrCreate, upsert, query, new. In the examples rec (or p) is a record.
local p = Player:findOne({ name = getPlayerName(pid) })
if p then
p.gold = p.gold - 50
p.stats = p.stats or {}
p.stats.potionsBought = (p.stats.potionsBought or 0) + 1
p:save() -- UPDATE players SET gold = ..., stats = ... WHERE id = ...
endMethods
save
rec:save(tx?)Writes the record to the database: a new record (Model:new) is inserted, an existing one is updated -
only the fields changed since it was read or last saved (nothing at all when nothing changed). The
record is refreshed with what the database stored (ids, defaults, updated_at). Returns the record.
Two copies of the same row saved one after another simply overwrite each other's changes - for counters
and currencies use increment.
p.name = "Diego the Great"
p:save()| Parameter | Type | Description |
|---|---|---|
tx (optional) | Transaction | Save inside this transaction (the tx of Database:transaction). |
Returns: Record - The record.
delete
rec:delete(tx?)Deletes the row of the record from the database. Returns true when a row was deleted.
| Parameter | Type | Description |
|---|---|---|
tx (optional) | Transaction | Delete inside this transaction. |
Returns: boolean - false = the row was already gone (or the record was never saved).
reload
rec:reload(tx?)Reads the row again from the database - fields changed meanwhile (by other code or another server) come
back, unsaved changes of the record are dropped. Loaded relations stay as they were (load them again with
Model:loadRelations). Returns the record, or nil when the row no longer exists.
| Parameter | Type | Description |
|---|---|---|
tx (optional) | Transaction | Read inside this transaction. |
Returns: Record | nil - The record, or nil.
increment
rec:increment(field, amount?, tx?)Adds an amount to a number field in the database itself (gold = gold + amount) - safe when the same row
is changed elsewhere at the same moment - and returns the new value. Other unsaved changes of the record
stay unsaved.
local kills = p:increment("kills") -- + 1
local gold = p:increment("gold", -100) -- - 100| Parameter | Type | Description |
|---|---|---|
field | string | Name of the field. |
amount (optional) | number | Amount to add (negative = subtract). Default 1. |
tx (optional) | Transaction | Inside this transaction. |
Returns: number - The new value of the field.
toTable
rec:toTable()A plain table with the fields of the record (no methods), loaded relations included (as plain tables
too) - for json.encode, sending to a client with triggerClientEvent, or keeping a copy.
Returns: table - The fields.
isNew
rec:isNew()true for a record made with Model:new and not saved yet.
Returns: boolean - Whether the record is not in the database yet.
