KScript documentación
ES

Idioma

Traducido automáticamente del inglés, que es la versión original.

campos y métodos de model

Un campo es un dato fijo sobre el valor, que se lee con un punto y sin corchetes: $value.name. Un método recibe argumentos o realiza una acción, y se llama con ->: $value->name(arguments), o con el valor encadenado: $value |> name(arguments).

De KScript.Data

Estos necesitan <import package="KScript.Data" />import KScript.Data. Consulta KScript.Data.

#model->all() → Self[] KScript.Data

Todos los registros (sin incluir los eliminados lógicamente).
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->all()->map(fn(t) => $t.title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->all()->map(fn(t) => $t.title)

#model->average(column: Self.fields) → number KScript.Data

La media de una columna, o null cuando ninguna fila coincide.
ParámetroRecibe
column obligatorioSelf.fields
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->average(points)->round(2) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->average(points)->round(2)

#model->chunk(size: number, work: fn) KScript.Data

Lee las filas por lotes y llama a work con cada lote (y su número, empezando por 0): sirve para recorrer más filas de las que caben en memoria. Devuelve false desde work para detenerte.
ParámetroRecibe
size requirednumber
work obligatoriofn

Los argumentos pueden tener nombre: ->chunk(…, work: …).

Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<fn name="show" params="batch: list, n: int">
  <echo>{ $n }: { $batch->map(fn(t) => $t.title)->join(', ') }</echo>
</fn>
<do>Task->order_by(id)->chunk(2, @show)</do>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
fn show(batch: list, n: int) {
  echo "{ $n }: { $batch->map(fn(t) => $t.title)->join(', ') }"
}
Task->order_by(id)->chunk(2, @show)

#model->count() → number KScript.Data

Cuántas filas coinciden.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->count() } tasks, { Task->where(done: false)->count() } to do</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo "{ Task->count() } tasks, { Task->where(done: false)->count() } to do"

#model->create(values...: Self) → Self KScript.Data

Comprueba los valores contra el modelo, guarda un registro nuevo y lo devuelve: User->create({ name: 'Joan', email: 'joan@example.com' }) o User->create(name: 'Joan', ...). Los campos protegidos se omiten.
ParámetroRecibe
valuesSelf, los que quieras
Ejemplo
<import package="KScript.Data" />
<model name="Note" fields="text: string, pinned: bool = false" />
<do>$db->create_table(Note)</do>
<let name="note" value="Note->create(text: 'Buy milk')" />
<echo>{ $note.id }: { $note.text }, pinned: { $note.pinned }</echo>
import KScript.Data
model Note {
  text: string
  pinned: bool = false
}
$db->create_table(Note)
$note = Note->create(text: 'Buy milk')
echo "{ $note.id }: { $note.text }, pinned: { $note.pinned }"

#model->cursor_paginate(per_page?: number, after?, key?: string, descending?: bool) → map KScript.Data

Lee una página usando una clave única y no nula (por defecto, la clave del modelo). Devuelve { items, has_more, next }; pasa next como after para continuar.
ParámetroRecibe
per_page opcionalnumber
after opcionalcualquier valor
key opcionalstring
descending opcionalun indicador: descending o not descending

Los argumentos pueden tener nombre: ->cursor_paginate(…, after: …, key: …).

Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<let name="page" value="Task->cursor_paginate(2)" />
<echo>{ $page.items->map(fn(t) => $t.title) }, more: { $page.has_more }</echo>
<let name="rest" value="Task->cursor_paginate(2, after: $page.next)" />
<echo>{ $rest.items->map(fn(t) => $t.title) }, more: { $rest.has_more }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
$page = Task->cursor_paginate(2)
echo "{ $page.items->map(fn(t) => $t.title) }, more: { $page.has_more }"
$rest = Task->cursor_paginate(2, after: $page.next)
echo "{ $rest.items->map(fn(t) => $t.title) }, more: { $rest.has_more }"

#model->decrement(column: Self.fields, by?: number) → number KScript.Data

Resta a una columna numérica de cada fila que coincida (1 por defecto). Devuelve cuántas filas cambiaron.
ParámetroRecibe
column obligatorioSelf.fields
by opcionalnumber

Los argumentos pueden tener nombre: ->decrement(…, by: …).

Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<do>Task->where(title: 'Ship it')->decrement(points)</do>
<echo>{ Task->where(title: 'Ship it')->value(points) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
Task->where(title: 'Ship it')->decrement(points)
echo Task->where(title: 'Ship it')->value(points)

#model->delete() → number KScript.Data

Elimina cada fila que coincida: los modelos que extienden SoftDeletes solo las marcan como eliminadas. Devuelve cuántas.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->where(done: true)->delete() } deleted</echo>
<echo>{ Task->count() } left, { Task->with_trashed()->count() } kept to restore</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo "{ Task->where(done: true)->delete() } deleted"
echo "{ Task->count() } left, { Task->with_trashed()->count() } kept to restore"

#model->distinct() → query KScript.Data

Omite las filas que repiten una anterior, en las columnas seleccionadas.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->select(done)->distinct()->count() }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->select(done)->distinct()->count()

#model->exists() → bool KScript.Data

Verdadero cuando alguna fila coincide.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->where(done: true)->exists() } { Task->where(points: 99)->exists() }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo "{ Task->where(done: true)->exists() } { Task->where(points: 99)->exists() }"

#model->fake(values...: Self) → Self KScript.Data

Guarda un registro con valores inventados para los campos que los necesiten, y estos valores: User->fake(role: 'admin'). Los campos opcionales y los que tienen valor por defecto se dejan al modelo, y una relación obligatoria también recibe un registro falso. Para pruebas y seeders.
ParámetroRecibe
valuesSelf, los que quieras
Ejemplo
<import package="KScript.Data" />
<model name="Person" fields="name: string, email: email" />
<do>$db->create_table(Person)</do>
<let name="joan" value="Person->fake(name: 'Joan')" />
<echo>{ $joan.name } { $joan.email->ends_with('@example.com') }</echo>
import KScript.Data
model Person {
  name: string
  email: email
}
$db->create_table(Person)
$joan = Person->fake(name: 'Joan')
echo "{ $joan.name } { $joan.email->ends_with('@example.com') }"

#model->fake_many(count: number, values...: Self) → Self[] KScript.Data

Guarda count registros falsos, cada uno con estos valores, y los devuelve: Post->fake_many(3, author: $joan).
ParámetroRecibe
count obligatorionumber
valuesSelf, los que quieras

Los argumentos pueden tener nombre: ->fake_many(…, values: …).

Ejemplo
<import package="KScript.Data" />
<model name="Person" fields="name: string, email: email" />
<do>$db->create_table(Person)</do>
<let name="people" value="Person->fake_many(3)" />
<echo>{ $people->count() } made, { Person->count() } saved</echo>
import KScript.Data
model Person {
  name: string
  email: email
}
$db->create_table(Person)
$people = Person->fake_many(3)
echo "{ $people->count() } made, { Person->count() } saved"

#model->find(id) → Self? KScript.Data

El registro con esta clave, o null.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->find(1).title }</echo>
<echo>{ Task->find(99) ?? 'none' }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->find(1).title
echo Task->find(99) ?? 'none'

#model->find_or_fail(id) → Self KScript.Data

El registro con esta clave, o un error ModelNotFound (un 404 en una ruta).
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<try>
  <do>Task->find_or_fail(99)</do>
  <catch type="ModelNotFound" as="e">
    <echo>{ $e.type }: { $e.message }</echo>
  </catch>
</try>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
try {
  Task->find_or_fail(99)
} catch ModelNotFound as e {
  echo "{ $e.type }: { $e.message }"
}

#model->first() → Self? KScript.Data

La primera fila, o null si ninguna coincide.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<let name="task" value="Task->order_by(points)->first()" />
<echo>{ $task.title }</echo>
<echo>{ Task->where(points: 99)->first() ?? 'none' }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
$task = Task->order_by(points)->first()
echo $task.title
echo Task->where(points: 99)->first() ?? 'none'

#model->first_or_create(match: map, values?: map) → Self KScript.Data

El primer registro que coincide, o uno nuevo creado a partir de ambos mapas.
ParámetroRecibe
match obligatoriomap
values opcionalmap

Los argumentos pueden tener nombre: ->first_or_create(…, values: …).

Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<let name="plan" value="Task->first_or_create({ title: 'Plan' }, { points: 2 })" />
<let name="again" value="Task->first_or_create({ title: 'Plan' })" />
<echo>{ $plan.points } points; same record: { $again.id == $plan.id }; { Task->count() } tasks</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
$plan = Task->first_or_create({ title: 'Plan' }, { points: 2 })
$again = Task->first_or_create({ title: 'Plan' })
echo "{ $plan.points } points; same record: { $again.id == $plan.id }; { Task->count() } tasks"

#model->first_or_fail() → Self KScript.Data

La primera fila, o un error ModelNotFound (un 404 en una ruta) si ninguna coincide.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<try>
  <do>Task->where(points: 99)->first_or_fail()</do>
  <catch type="ModelNotFound" as="e">
    <echo>{ $e.type }</echo>
  </catch>
</try>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
try {
  Task->where(points: 99)->first_or_fail()
} catch ModelNotFound as e {
  echo $e.type
}

#model->first_or_new(match: map, values?: map) → Self KScript.Data

El primer registro que coincide, o uno nuevo creado con ambos mapas que aún no está guardado: llama a ->save() para conservarlo.
ParámetroRecibe
match obligatoriomap
values opcionalmap

Los argumentos pueden tener nombre: ->first_or_new(…, values: …).

Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<let name="plan" value="Task->first_or_new({ title: 'Plan' }, { points: 2 })" />
<echo>{ $plan->is_saved() }</echo>
<do>$plan->save()</do>
<echo>{ Task->count() } tasks</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
$plan = Task->first_or_new({ title: 'Plan' }, { points: 2 })
echo $plan->is_saved()
$plan->save()
echo "{ Task->count() } tasks"

#model->force_delete() → number KScript.Data

Elimina cada fila que coincide, incluso en modelos que extienden SoftDeletes. Devuelve cuántas.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->where(done: true)->force_delete() } removed</echo>
<echo>{ Task->with_trashed()->count() } left in the table</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo "{ Task->where(done: true)->force_delete() } removed"
echo "{ Task->with_trashed()->count() } left in the table"

#model->get() → Self[] KScript.Data

Ejecuta la consulta: una lista de registros (mapas, para una tabla sin modelo).
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<for each="task" in="Task->where(done: false)->order_by(title)->get()">
  <echo>{ $task.title }: { $task.points }</echo>
</for>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
for task in Task->where(done: false)->order_by(title)->get() {
  echo "{ $task.title }: { $task.points }"
}

#model->group_by(columns...: Self.fields) → grouped_query KScript.Data

Divide las filas en grupos con los mismos valores en estas columnas, para obtener totales por grupo: Order->group_by(status)->count() devuelve { open: 3, paid: 5 }. Con dos columnas, cada total va en un mapa dentro de otro mapa.
ParámetroRecibe
columnsSelf.fields, los que quieras
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->group_by(done)->count() }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->group_by(done)->count()

#model->in_random_order() → query KScript.Data

Lee las filas en un orden aleatorio, distinto cada vez: Quote->in_random_order()->first().
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->in_random_order()->count() } tasks, in a new order each time</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo "{ Task->in_random_order()->count() } tasks, in a new order each time"

#model->increment(column: Self.fields, by?: number) → number KScript.Data

Suma a una columna numérica en todas las filas que coinciden (1 por defecto). Devuelve cuántas filas cambiaron.
ParámetroRecibe
column obligatorioSelf.fields
by opcionalnumber

Los argumentos pueden tener nombre: ->increment(…, by: …).

Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<do>Task->where(title: 'Ship it')->increment(points, by: 2)</do>
<echo>{ Task->where(title: 'Ship it')->value(points) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
Task->where(title: 'Ship it')->increment(points, by: 2)
echo Task->where(title: 'Ship it')->value(points)

#model->insert(rows) → number KScript.Data

Añade filas: un mapa o una lista de mapas. En un modelo, cada uno se comprueba como en ->create(). Devuelve cuántas se han añadido.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->insert([{ title: 'Plan' }, { title: 'Review', points: 2 }]) } added</echo>
<echo>{ Task->count() } tasks</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo "{ Task->insert([{ title: 'Plan' }, { title: 'Review', points: 2 }]) } added"
echo "{ Task->count() } tasks"

#model->latest(column?: Self.fields) → query KScript.Data

Ordena de más reciente a más antiguo por la columna indicada. Por defecto usa created_at, o la clave primaria en un modelo que no extiende Timestamps.
ParámetroRecibe
column opcionalSelf.fields
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->latest(points)->value(title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->latest(points)->value(title)

#model->limit(count: number) → query KScript.Data

Lee como máximo este número de filas.
ParámetroRecibe
count obligatorionumber
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->order_by(title)->limit(2)->pluck(title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->order_by(title)->limit(2)->pluck(title)

#model->lock_for_update() → query KScript.Data

Bloquea las filas leídas hasta que termine la transacción, para que nadie más las modifique antes. Úsalo dentro de una transacción. En SQLite, que bloquea toda la base de datos durante las escrituras de una transacción, no cambia nada.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<transaction>
  <let name="next" value="Task->where(done: false)->order_by(id)->lock_for_update()->first()" />
  <do>$next->update(done: true)</do>
</transaction>
<echo>{ Task->where(done: true)->count() } done</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
transaction {
  $next = Task->where(done: false)->order_by(id)->lock_for_update()->first()
  $next->update(done: true)
}
echo "{ Task->where(done: true)->count() } done"

#model->max(column: Self.fields) → Self[column] KScript.Data

El mayor valor de una columna, o null si ninguna fila coincide.
ParámetroRecibe
column obligatorioSelf.fields
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->max(points) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->max(points)

#model->min(column: Self.fields) → Self[column] KScript.Data

El menor valor de una columna, o null si ninguna fila coincide.
ParámetroRecibe
column obligatorioSelf.fields
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->min(points) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->min(points)

#model->offset(count: number) → query KScript.Data

Omite primero este número de filas.
ParámetroRecibe
count obligatorionumber
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->order_by(title)->offset(1)->limit(1)->pluck(title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->order_by(title)->offset(1)->limit(1)->pluck(title)

#model->oldest(column?: Self.fields) → query KScript.Data

Ordena de más antiguo a más reciente por la columna indicada. Por defecto usa created_at, o la clave primaria en un modelo que no extiende Timestamps.
ParámetroRecibe
column opcionalSelf.fields
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->oldest(points)->value(title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->oldest(points)->value(title)

#model->only_trashed() → query KScript.Data

Para modelos que extienden SoftDeletes: lee solo los registros eliminados.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<do>Task->where(done: true)->delete()</do>
<echo>{ Task->only_trashed()->pluck(title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
Task->where(done: true)->delete()
echo Task->only_trashed()->pluck(title)

#model->or_where(conditions...: Self) → query KScript.Data

Como ->where(), unido con or: filas que cumplen las condiciones hasta ahora, o estas.
ParámetroRecibe
conditionsSelf, los que quieras
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->where(done: true)->or_where(points: 5)->pluck(title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->where(done: true)->or_where(points: 5)->pluck(title)

#model->order_by(columns...: Self.fields) → query KScript.Data

Ordena las filas: ->order_by(name), ->order_by(created_at: desc, name: asc).
ParámetroRecibe
columnsSelf.fields, los que quieras
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->order_by(points: desc)->pluck(title) }</echo>
<echo>{ Task->order_by(done, title)->pluck(title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->order_by(points: desc)->pluck(title)
echo Task->order_by(done, title)->pluck(title)

#model->paginate(per_page?: number, page?) → map KScript.Data

Una página de filas: { items, page, per_page, total, last_page, from, to, has_more }. per_page es 15 por defecto; page (1 por defecto) puede ser un número o texto como $query.page, y el texto que no es un número equivale a la página 1.
ParámetroRecibe
per_page opcionalnumber
page opcionalcualquier valor

Los argumentos pueden tener nombre: ->paginate(…, page: …).

Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<let name="page" value="Task->order_by(id)->paginate(2, page: 1)" />
<echo>{ $page.items->map(fn(t) => $t.title) }: page { $page.page } of { $page.last_page }, { $page.total } in all</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
$page = Task->order_by(id)->paginate(2, page: 1)
echo "{ $page.items->map(fn(t) => $t.title) }: page { $page.page } of { $page.last_page }, { $page.total } in all"

#model->pluck(column: Self.fields) → Self[column][] KScript.Data

Una columna de cada fila que coincida, como lista: User->pluck(email).
ParámetroRecibe
column obligatorioSelf.fields
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->order_by(title)->pluck(title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->order_by(title)->pluck(title)

#model->query() → query KScript.Data

Una consulta sobre el modelo sin condiciones todavía, para seguir construyéndola.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<let name="query" value="Task->query()" />
<let name="query" value="$query->where(done: false)" />
<echo>{ $query->count() } to do</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
$query = Task->query()
$query = $query->where(done: false)
echo "{ $query->count() } to do"

#model->restore() → number KScript.Data

Para modelos que extienden SoftDeletes: restaura los registros eliminados que coincidan. Devuelve cuántos son.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<do>Task->where(done: true)->delete()</do>
<echo>{ Task->only_trashed()->restore() } restored, { Task->count() } tasks</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
Task->where(done: true)->delete()
echo "{ Task->only_trashed()->restore() } restored, { Task->count() } tasks"

#model->select(columns...: Self.fields) → query KScript.Data

Lee solo estas columnas: ->select(id, name). Los registros tendrán null en las demás.
ParámetroRecibe
columnsSelf.fields, los que quieras
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<let name="task" value="Task->select(id, title)->first()" />
<echo>{ $task.title }: { $task.points ?? 'not read' }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
$task = Task->select(id, title)->first()
echo "{ $task.title }: { $task.points ?? 'not read' }"

#model->skip_locked() → query KScript.Data

Con ->lock_for_update(): omite las filas que otra transacción tiene bloqueadas, en lugar de esperar. Es útil para tomar trabajos de una cola. En SQLite, que no tiene bloqueos de fila, no cambia nada.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<transaction>
  <let name="next" value="Task->where(done: false)->order_by(id)->lock_for_update()->skip_locked()->first()" />
  <echo>{ $next.title }</echo>
</transaction>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
transaction {
  $next = Task->where(done: false)->order_by(id)->lock_for_update()->skip_locked()->first()
  echo $next.title
}

#model->sole() → Self KScript.Data

La única fila que coincide: si no coincide ninguna, se produce un error ModelNotFound (un 404 en una ruta); si coinciden varias, un error MultipleRecordsFound.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->where(title: 'Fix bug')->sole().points }</echo>
<try>
  <do>Task->where(done: false)->sole()</do>
  <catch type="MultipleRecordsFound" as="e">
    <echo>{ $e.type }</echo>
  </catch>
</try>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->where(title: 'Fix bug')->sole().points
try {
  Task->where(done: false)->sole()
} catch MultipleRecordsFound as e {
  echo $e.type
}

#model->sql() → map KScript.Data

El SQL que ejecuta la consulta y sus parámetros, sin ejecutarla: { sql, params }.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<let name="query" value="Task->where(done: false)->order_by(title)->sql()" />
<echo>{ $query.sql }</echo>
<echo>{ $query.params->convert(to: json) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
$query = Task->where(done: false)->order_by(title)->sql()
echo $query.sql
echo $query.params->convert(to: json)

#model->sum(column: Self.fields) → number KScript.Data

El total de una columna en las filas que coinciden (0 si ninguna coincide).
ParámetroRecibe
column obligatorioSelf.fields
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->sum(points) } points, { Task->where(done: false)->sum(points) } left</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo "{ Task->sum(points) } points, { Task->where(done: false)->sum(points) } left"

#model->update(values...: Self) → number KScript.Data

Establece columnas en cada fila que coincida, sin leerlas: ->update(active: false). Devuelve cuántas filas han cambiado.
ParámetroRecibe
valuesSelf, los que quieras
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->where(done: false)->update(done: true) } changed</echo>
<echo>{ Task->where(done: true)->count() } done</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo "{ Task->where(done: false)->update(done: true) } changed"
echo "{ Task->where(done: true)->count() } done"

#model->update_or_create(match: map, values?: map) → Self KScript.Data

Actualiza el primer registro que coincida con los valores, o crea uno con ambos mapas. Devuelve el registro: Product->update_or_create({ sku: $item.sku }, { price: $item.price }).
ParámetroRecibe
match obligatoriomap
values opcionalmap

Los argumentos pueden tener nombre: ->update_or_create(…, values: …).

Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<let name="ship" value="Task->update_or_create({ title: 'Ship it' }, { points: 8 })" />
<let name="plan" value="Task->update_or_create({ title: 'Plan' }, { points: 1 })" />
<echo>{ $ship.points } points; { Task->count() } tasks</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
$ship = Task->update_or_create({ title: 'Ship it' }, { points: 8 })
$plan = Task->update_or_create({ title: 'Plan' }, { points: 1 })
echo "{ $ship.points } points; { Task->count() } tasks"

#model->upsert(row: map, key?: string) → number KScript.Data

Inserta una fila o actualiza los campos indicados de forma atómica ante un conflicto de unicidad. La clave debe nombrar una columna única. El recuento devuelto es el de filas afectadas que informa el proveedor.
ParámetroRecibe
row obligatoriomap
key opcionalstring

Los argumentos pueden tener nombre: ->upsert(…, key: …).

Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<do>Task->upsert({ title: 'Ship it', points: 8 }, key: 'title'); Task->upsert({ title: 'Plan', points: 1 }, key: 'title')</do>
<echo>{ Task->where(title: 'Ship it')->value(points) } points, { Task->count() } tasks</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
Task->upsert({ title: 'Ship it', points: 8 }, key: 'title')
Task->upsert({ title: 'Plan', points: 1 }, key: 'title')
echo "{ Task->where(title: 'Ship it')->value(points) } points, { Task->count() } tasks"

#model->value(column: Self.fields) → Self[column] KScript.Data

Una columna de la primera fila, o null.
ParámetroRecibe
column obligatorioSelf.fields
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->where(done: true)->value(title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->where(done: true)->value(title)

#model->when(test, then: fn, otherwise?: fn) → query KScript.Data

Modifica la consulta solo cuando la condición sea verdadera: ->when($search != null, fn(q) => $q->where(fn(u) => $u.name->contains($search))).
ParámetroRecibe
test obligatoriocualquier valor
then obligatoriofn
otherwise opcionalfn

Los argumentos pueden tener nombre: ->when(…, then: …, otherwise: …).

Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<let name="search" value="'docs'" />
<echo>{ Task->when($search != null, fn(q) => $q->where(fn(t) => $t.title->contains($search)))->pluck(title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
$search = 'docs'
echo Task->when($search != null, fn(q) => $q->where(fn(t) => $t.title->contains($search)))->pluck(title)

#model->where(conditions...: Self) → query KScript.Data

Conserva las filas que coinciden: una lambda compilada a SQL, fn(u) => $u.age >= 18 and $u.name->starts_with('J'), o nombres y valores, role: admin, team_id: 3 (una lista significa cualquiera de ellos; null significa ninguno).
ParámetroRecibe
conditionsSelf, los que quieras
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->where(done: false)->pluck(title) }</echo>
<echo>{ Task->where(fn(t) => $t.points >= 3)->count() }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->where(done: false)->pluck(title)
echo Task->where(fn(t) => $t.points >= 3)->count()

#model->where_not(conditions...: Self) → query KScript.Data

Excluye las filas que coinciden.
ParámetroRecibe
conditionsSelf, los que quieras
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<echo>{ Task->where_not(done: true)->pluck(title) }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
echo Task->where_not(done: true)->pluck(title)

#model->with(relations...: Self.fields(relations: only)) → query KScript.Data

Carga las relaciones junto con los registros, con una consulta por relación en lugar de una por registro: ->with(author, tags), ->with(posts.tags), o ->with(posts: fn(q) => $q->where(published: true)) para cargar solo algunas.
ParámetroRecibe
relationsSelf.fields(relations: only), cualquier número de ellas
Ejemplo
<import package="KScript.Data" />
<model name="Author" fields="name: string, posts: Post[]" />
<model name="Post" fields="title: string, published: bool = false, author: Author" />
<do>$db->create_table(Author); $db->create_table(Post)</do>
<let name="ada" value="Author->create(name: 'Ada')" />
<do>Post->create(title: 'Notes', published: true, author: $ada); Post->create(title: 'Draft', author: $ada)</do>
<for each="post" in="Post->with(author)->order_by(title)->get()">
  <echo>{ $post.title } by { $post.author.name }</echo>
</for>
import KScript.Data
model Author {
  name: string
  posts: Post[]
}
model Post {
  title: string
  published: bool = false
  author: Author
}
$db->create_table(Author)
$db->create_table(Post)
$ada = Author->create(name: 'Ada')
Post->create(title: 'Notes', published: true, author: $ada)
Post->create(title: 'Draft', author: $ada)
for post in Post->with(author)->order_by(title)->get() {
  echo "{ $post.title } by { $post.author.name }"
}

#model->with_count(relations...: Self.fields(relations: only)) → query KScript.Data

Cuenta una relación de lista para cada registro, como un campo con su nombre: ->with_count(posts) da a cada usuario posts_count. ->with_count(posts: fn(q) => $q->where(published: true)) cuenta solo algunas.
ParámetroRecibe
relationsSelf.fields(relations: only), cualquier número de ellas
Ejemplo
<import package="KScript.Data" />
<model name="Author" fields="name: string, posts: Post[]" />
<model name="Post" fields="title: string, published: bool = false, author: Author" />
<do>$db->create_table(Author); $db->create_table(Post)</do>
<let name="ada" value="Author->create(name: 'Ada')" />
<do>Post->create(title: 'Notes', published: true, author: $ada); Post->create(title: 'Draft', author: $ada)</do>
<let name="author" value="Author->with_count(posts)->first()" />
<echo>{ $author.name } has { $author.posts_count } posts</echo>
import KScript.Data
model Author {
  name: string
  posts: Post[]
}
model Post {
  title: string
  published: bool = false
  author: Author
}
$db->create_table(Author)
$db->create_table(Post)
$ada = Author->create(name: 'Ada')
Post->create(title: 'Notes', published: true, author: $ada)
Post->create(title: 'Draft', author: $ada)
$author = Author->with_count(posts)->first()
echo "{ $author.name } has { $author.posts_count } posts"

#model->with_trashed() → query KScript.Data

Para modelos que extienden SoftDeletes: incluye los registros eliminados, que las consultas omiten por defecto.
Ejemplo
<import package="KScript.Data" />
<model name="Task" with="SoftDeletes" fields="title: string, done: bool = false, points: int = 1" unique="title" />
<do>$db->create_table(Task); Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])</do>
<do>Task->where(done: true)->delete()</do>
<echo>{ Task->count() } of { Task->with_trashed()->count() }</echo>
import KScript.Data
model Task(unique: [title]) extends SoftDeletes {
  title: string
  done: bool = false
  points: int = 1
}
$db->create_table(Task)
Task->insert([{ title: 'Write docs', points: 3 }, { title: 'Fix bug', done: true, points: 2 }, { title: 'Ship it', points: 5 }])
Task->where(done: true)->delete()
echo "{ Task->count() } of { Task->with_trashed()->count() }"

Métodos de cualquier tipo