Download the PHP package ristocloud-group/php-activerecord without Composer

On this page you can find all versions of the php package ristocloud-group/php-activerecord. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package php-activerecord

PHP ActiveRecord

CI Coverage

This is a fork maintained by Ristocloud Group S.r.l.

It is based on zamzar/php-activerecord (itself a fork of the original jpfuentes2/php-activerecord). We vendor it into our own applications and maintain it — fixing bugs and keeping it running on modern PHP and database versions. It is not affiliated with, nor endorsed by, the original authors.

Originally created by:

Upstream documentation: http://www.phpactiverecord.org/

Introduction

A brief summarization of what ActiveRecord is:

Active record is an approach to access data in a database. A database table or view is wrapped into a class, thus an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database; when an object is updated, the corresponding row in the table is also updated. The wrapper class implements accessor methods or properties for each column in the table or view.

More details can be found here.

This implementation is inspired and thus borrows heavily from Ruby on Rails' ActiveRecord. We have tried to maintain their conventions while deviating mainly because of convenience or necessity. Of course, there are some differences which will be obvious to the user if they are familiar with rails.

Minimum Requirements

Supported Databases

These are policy minimums; composer.json carries no database-version constraint. Continuous integration runs the full test suite across PHP 8.3, 8.4 and 8.5 against MySQL 8.4 & 9.7, MariaDB 10.11, 11.4, 11.8 & 12.3, PostgreSQL 15, 16, 17 & 18, and SQLite 3. The Oracle (oci) adapter was removed in v1.8.0.

Features

Installation

Install it with Composer from Packagist:

[!IMPORTANT] Install the package from Packagist, not straight from this GitHub repository. If your composer.json still lists this repository under repositories (a vcs entry pointing at https://github.com/ristocloud-group/php-activerecord), remove that entry, require a released version instead of dev-master, and run composer update ristocloud-group/php-activerecord.

The library loads only through Composer's autoloader: require 'vendor/autoload.php';. It has no other entry point. Composer 2.7.7 or newer gives a clean optimized dump (composer dump-autoload --optimize); older Composer 2 prints PSR-4 "does not comply … Skipping" warnings for the classes in lib/'s subfolders but still loads every class. To read the installed version, call \Composer\InstalledVersions::getPrettyVersion('ristocloud-group/php-activerecord').

Setup is very easy and straight-forward. There are essentially only two configuration points you must concern yourself with:

  1. Configuring your database connections.
  2. Setting the database connection to use for your environment.

Example:

Alternatively (without a closure):

MariaDB uses the same mysql:// connection scheme (and the MySQL adapter) as MySQL.

Connection URLs

Connections are configured with URLs of the form:

The query string may carry two optional parameters, separated by & as usual:

SQLite needs no credentials or database name — the URL is a path to an existing database file:

PHP ActiveRecord will default to use your development database. For testing or production, you simply set the default connection according to your current environment ('test' or 'production'):

Once you have configured these settings you are done. ActiveRecord takes care of the rest for you. It does not require that you map your table schema to yaml/xml files. It will query the database for this information and cache it so that it does not make multiple calls to the database for a single schema.

Optional: strict mass assignment

By default, mass assignment (new Model($attributes), set_attributes(), update_attributes(), create()) drops every attribute blocked by a model's $attr_accessible / $attr_protected and, if a logger is configured, logs a warning. Turn on strict mode to throw an ActiveRecord\MassAssignmentException instead — raised before anything is assigned, its message lists every blocked attribute. It is global and off by default; assigning a single attribute ($model->name = …) is not affected. The foreign key that association builders (build_* / create_*) inject is assigned directly, like Rails: it needs no $attr_accessible entry and is never dropped or reported. The attributes passed to a builder are guarded as usual, and that includes a foreign key passed there with a value: the builder then injects nothing for it, so a blocked one is dropped (the record gets no foreign key) or, in strict mode, throws. A foreign key passed as null counts as not passed and is replaced by the injected value.

Optional: tinyint(1) as an integer (MySQL/MariaDB)

On MySQL and MariaDB a tinyint(1) column is a boolean by convention (the expansion of MySQL's own BOOLEAN): its values and default read as PHP true/false. An AUTO_INCREMENT tinyint(1) and every wider tinyint stay integers. A legacy schema that stores small integers (4, -1, …) in tinyint(1) can turn the convention off: the column is then an integer, as in 1.7.1, so its values are read, written back and serialised as they are. It is global and on by default. Column types are read once per table, so set it in Config::initialize(), before the first model is used; the schema cache keeps the two settings apart.

Optional: caching the schema

php-activerecord introspects each table's schema (columns, types, primary key) from the database. Within a single request this is kept in memory, but PHP's shared-nothing model means it is re-introspected on every request. To persist it across requests, configure an external cache. Three backends are bundled:

Memcached — requires the memcached PHP extension:

File — a filesystem cache (added by this fork for hosts without memcached); no extension required:

The file backend stores one serialized file per cache key inside the directory you pass (creating the directory if it does not exist), and reads it back with unserialize().

The file backend also honors the expire option: each entry stores an expiry timestamp and is treated as a miss once it lapses (deleted lazily on the next read). Writes are atomic (temp file + rename). Behavior change: because the default expire is 30 seconds, file entries that previously persisted forever now expire after 30s by default — pass ['expire' => 0] to keep entries until you flush() them. Files written by older versions are treated as a miss and regenerated, so no manual purge is needed when upgrading.

Redis — requires the predis/predis Composer package (composer require predis/predis); no PHP extension needed:

Connection parameters are taken from the DSN, including its query string, so any Predis connection parameter is reachable — e.g. TLS and tuning:

The same redis:// DSN targets Redis 6/7/8 and Valkey 7/8/9 interchangeably; the adapter is exercised against all six in CI. Values are serialized on write and unserialized on read. ActiveRecord\Cache::flush() deletes only the keys under the configured namespace (via SCAN/DEL); with no namespace it falls back to FLUSHDB, which clears the whole selected Redis database — set a namespace when the Redis instance is shared. Do not pass a Predis prefix client option for key isolation: Predis does not apply prefix to the plain SCAN command that namespace-scoped flush() relies on, so keys end up stored under prefix + key while flush() only matches namespace::*, silently deleting nothing — use the namespace option instead, which flush() already understands.

ActiveRecord\Cache::flush() invalidates the cache for any backend (for the file cache it deletes the cached files) — for example after running a schema migration. All backends accept a namespace option that prefixes every cache key, useful when several applications share one cache store.

The cache is lock-free: at each expiry, concurrent requests all recompute the cached value once (a brief stampede). For very hot deployments raise expire (or set it to 0). Prefer a local filesystem for the file backend — TTLs rely on the host clock, so shared storage (NFS) across clock-skewed hosts can expire entries early or late.

Backend Requirement TTL (expire) Persistence Namespace / flush Concurrency Best for
Memcached memcached PHP extension Yes (server-side) In-memory, evictable namespace prefix; flush() clears the whole server Atomic server-side TTL Existing memcached infra
File none Yes (since this fork) On disk until expiry/flush namespace prefix; flush() deletes files Lock-free; atomic writes, lazy GC, local-FS assumption Single host, no extra services
Redis / Valkey predis/predis package Yes (server-side) In-memory (optionally persisted by the server) namespace-scoped SCAN/DEL, else FLUSHDB Atomic server-side TTL Shared/networked cache, HA

Hash conditions

In a conditions hash (['conditions' => ['name' => 'Tito']], also for update_all / delete_all) every key is a column name, always quoted as identifiers and never spliced in as SQL. A key may name its table ('books.name', e.g. with joins), and a partly quoted name is quoted part by part ('`books`.name' → `books`.`name`); with joins an unqualified key that names a column of the model gets the model's table, and any other one (a column of a joined table) stays as written. With the from option every key is still qualified, with the from table, as before. The columns of the model include the ones every table has without listing them (_rowid on MySQL and MariaDB; rowid, oid and _rowid_ on SQLite; ctid, xmin, xmax, cmin, cmax and tableoid on Postgres), which are qualified too. On SQLite, PRAGMA table_info omits generated columns and the hidden columns of a virtual table, so they are not seen as columns of the model and stay as written: a joined table with a column of the same name makes such a key ambiguous, so write it qualified ('books.total'). Keys that name the same column ('id', '`id`', 'books.id', and an $alias_attribute name and the column it stands for) are all kept and ANDed. An attribute name whose column is named differently is mapped to that column, also for update_all / delete_all (and for the keys of an update_all set hash and of upsert): 'space_name' → space name, 'dash_name' → dash-name, and on Postgres, whose quoted names are case-sensitive, a mixed-case 'some_date' → some_Date (MySQL and SQLite match it as is); space and hyphen differences are mapped on every adapter, and upsert's $unique_by / $update names are mapped too. Written next to the column's own name, two conditions are kept and ANDed, whereas in a set hash or an upsert row the later key wins. An expression such as 'LOWER(name)' => 'tito' is one (unknown) column name, not a function call, so the database rejects it: write expressions as a positional condition instead, ['conditions' => ['LOWER(name) = ?', 'tito']].

An $alias_attribute name stands for its column in the conditions hash of find / all / first / last, count, exists, update_all and delete_all alike, in a relationship's declared conditions hash, and in every column name the query builder takes: with 'marquee' => 'name', ['marquee' => 'Warner Theatre'] reads as name = 'Warner Theatre'. A relationship's hash reads the names of its associated model, the one its load finds (the target of a has_many … through): its aliases and its attribute names ('space_name' for the column space name), in the lazy load and the eager include alike. An alias next to its column's own name keeps both conditions, ANDed, and any other key, a qualified one included, is written as before. In a through, which joins the middle table, a key the mapping changes (an alias, or an attribute name whose column is named differently) is named with the target's table, `venues`.`city`, so it stays unambiguous when the middle table has a column of the same name. Still write a key of the middle table qualified ('events.title'): unqualified, a name that is also an alias or an attribute name of the target names the target's column. So that a name is never ambiguous, an alias may not be named like a column of the model's own table, by the column's real name or by its attribute name ('space_name' for the column space name), nor like a column every table has without listing it (_rowid on MySQL and MariaDB; rowid, oid and _rowid_ on SQLite; ctid, xmin, xmax, cmin, cmax and tableoid on Postgres): such a model does not load, and its first use throws ActiveRecord\ConfigException, naming the model, the alias and the column. Names are compared as the database compares column names, regardless of case, except on Postgres ('Author_Id' is the column author_id on MySQL, MariaDB and SQLite, not on Postgres). The check reads the columns as the table loads, so a shadowing column it does not see (one added to the table afterwards, in a long-running process or behind a stale schema cache, or on SQLite a generated column, which PRAGMA table_info omits) leaves the alias winning in every condition; the next load with fresh metadata throws.

The identifiers-only guarantee relies on doubling the quote character, so it assumes a connection charset in which that byte cannot belong to a multibyte character: utf8mb4 / utf8 (the default) or a single-byte charset. Legacy multibyte MySQL charsets (gbk, big5, sjis / cp932, gb18030) are not covered.

delete_all() and update_all() read their argument as the finders do. delete_all() takes an options hash (conditions, limit, order), a conditions string, or, as count() / exists() do, a bare conditions hash: Author::delete_all(['name' => 'Tito']) deletes only the matching rows, and with no argument (or null / []) it still deletes every row. update_all() takes an options hash with set; a hash set also sets updated_at, unless it gives one or the model class is suspended with without_timestamps(), and a string set is sent as written (see Timestamps). A key gives updated_at by its column's name or attribute name, also pre-quoted or qualified with the model's table ('`authors`.`updated_at`'), and the column is then assigned once, the value given: MySQL and MariaDB take a qualified column in a SET, and Postgres and SQLite refuse it, as before. The other finder options are ignored, as before. An argument that could be misread throws ActiveRecordException before any SQL runs: a positional list (write ['conditions' => ['name = ?', 'Tito']]), a hash mixing option keys with other keys (Unknown key(s): …), an int, float or bool, and, for update_all(), a key beside set that is not an option, such as a column name, or an argument without set.

A statement terminator in the conditions SQL throws. The SQL of the conditions option, a string ('author_id > 1') or the first element of a positional list (['author_id > ?', 1]), must not hold a ; outside its string literals and comments: find / all / first / last, count, exists, update_all and delete_all throw ActiveRecordException before any SQL runs, and so does the load of a relationship whose declared conditions hold one (every database refused its statement before). MySQL, MariaDB and SQLite end the statement there and drop what follows it, the order and the limit among it, so a limited update_all() or delete_all() wrote every row it matched and a find read every row; Postgres refuses the statement. A ; with nothing after it is refused as well. A ; in a string literal ("name = 'a;b'"), in a comment or in a bound value (['name = ?', 'a;b']) is sent as before. A block comment left open throws too: a /* outside the string literals and comments with no */ after it ('author_id > 0 /* note'). SQLite runs it to the end of the statement, so a limited delete_all() deleted every row it matched; MySQL, MariaDB and Postgres refuse the statement. A closed comment, or a /* in a string literal, is sent as before. The other options (select, joins, from, group, having, order), the $where of a direct Table::update() / Table::delete() and find_by_sql() send their SQL as written, unread. The rule is the builder's (see Conditions).

Query builder

Every model also has an Eloquent-style fluent query builder, with Eloquent's names in snake_case. It sits on the engine that the finders (find, first, all, count, exists), update_all, delete_all, save, delete and upsert also run through, so a condition or an alias is read by the same rules whichever API builds the statement. Dates are the exception: the builder binds a DateTime in the format of its column, where the legacy finders keep the datetime format (see Conditions). It is additive: every existing static method keeps its meaning (see Legacy and builder side by side).

The terminals return arrays, as find('all') does: there is no collection class. The snippets of this section use the models of examples/query_builder/ (a Customer has many Invoices, and an invoice belongs to a customer), a runnable demonstration of the builder.

Entry points

Invoice::new_query() starts a query on a model: an ActiveRecord\Query, typed Query<Invoice>. The builder methods can also be called on the class itself: Invoice::where(...) is Invoice::new_query()->where(...). The forwarded names are listed in Query::FORWARDABLE, and each has a @method static tag on Model, so an IDE or PHPStan knows it, and its return type, without an extension.

A query is mutable, as in Eloquent: a builder method changes the query and returns that same object, and the terminals (get(), count(), ...) read it and leave it as it was. To go two ways from one point, fork it with clone(), which is a deep copy:

A query refuses what it cannot read at the call that gives it, not when it runs: an unknown operator, a negative limit, an empty column name, SQL written by hand that holds a statement terminator or leaves a block comment open, a relationship the model does not declare, ... Those are ActiveRecordExceptions (or a subclass, such as RelationshipException), and a database error is still a DatabaseException.

What a static call such as Invoice::something() reaches:

The builder does not go through a model's overrides of the legacy finders. A base class whose all() or find() adds a condition (a soft-delete filter, say) does not affect new_query() or the forwarded calls.

From Eloquent to snake_case

The names are Eloquent's in snakecase, with the `orvariants it has (orWhereisor_where,orWhereInis or_where_in`, ...):

Eloquent Here
where, orWhere, whereNot, orWhereNot where, or_where, where_not, or_where_not
whereIn, whereNotIn, whereNull, whereNotNull, whereBetween, whereNotBetween, whereBetweenColumns where_in, where_not_in, where_null, where_not_null, where_between, where_not_between, where_between_columns
whereColumn, whereRaw, whereLike, whereNotLike, whereAll, whereAny, whereNone, whereKey, whereKeyNot where_column, where_raw, where_like, where_not_like, where_all, where_any, where_none, where_key, where_key_not
select, addSelect, selectRaw, distinct, from, fromRaw select, add_select, select_raw, distinct, from, from_raw
join, leftJoin, rightJoin, crossJoin join, left_join, right_join, cross_join
orderBy, orderByDesc, orderByRaw, latest, oldest, reorder, inRandomOrder order_by, order_by_desc, order_by_raw, latest, oldest, reorder, in_random_order
groupBy, groupByRaw, having, orHaving, havingRaw, havingNull, havingNotNull, havingBetween group_by, group_by_raw, having, or_having, having_raw, having_null, having_not_null, having_between
limit, take, offset, skip, forPage limit, take, offset, skip, for_page
with, without, withOnly, when, unless, tap, clone with, without, with_only, when, unless, tap, clone
toSql, toRawSql, getBindings to_sql, to_raw_sql, get_bindings
get, first, firstOrFail, firstOr, sole, find, findOrFail, findMany, findOr, value, soleValue, pluck, exists, doesntExist get, first, first_or_fail, first_or, sole, find, find_or_fail, find_many, find_or, value, sole_value, pluck, exists, doesnt_exist
count, min, max, sum, avg, average count, min, max, sum, avg, average
chunk, chunkById, chunkByIdDesc, lazy, lazyById, lazyByIdDesc, cursor chunk, chunk_by_id, chunk_by_id_desc, lazy, lazy_by_id, lazy_by_id_desc, cursor
insert, update, delete, upsert insert, update, delete, upsert

Added here: joins() and left_joins() join by relationship name, readonly() flags the models a query finds as readonly, and Model::without_timestamps() suspends the timestamps of a model for a closure.

Eloquent's other builder features are not part of it: relationship queries (whereHas, withCount, ...), subqueries and unions, locks, increment / decrement, firstOrCreate and the other *OrCreate methods, pagination, query scopes, and the date, JSON and full-text wheres.

Legacy and builder side by side

Some names exist in both worlds. Called on the class, the legacy static runs; called on a query (new_query(), or after another builder call), the builder's runs. The legacy ones are unchanged, so existing code is not affected, except count and exists: there is one count and one exists, and the legacy ones run the builder's on the query of their options:

Name Legacy: Invoice::... Builder: Invoice::new_query()->...
find find(1), find(1, 2), find([1, 2]): a missing primary key throws RecordNotFound; the option forms find('first', ...) and find($options) return null, and find('all', ...) returns [] find(1) is the model, or null. find([1, 2]) is an array of the models found, a missing id left out. find_or_fail($id) throws RecordNotFound (with the legacy message) when an id is missing, find_many($ids) is the list form, and find_or($id, $callback) calls the callback instead of throwing. A one-column primary key only
first first($options); last($options) reverses the order (by the primary key when there is none) first() is LIMIT 1 in the query's own order, none implied, and returns a model or null. first_or_fail(), first_or($callback) and sole() are the strict forms. There is no last(): reverse the order
count count($options) or primary key values: the builder's count() of the query of those options, so it counts the rows of the result too (a group its groups, a limit or an offset the rows of the window), always an int count($column = '*') counts the rows of the result, so a grouped query counts its groups. count('note') is COUNT(note), where Invoice::count('note') looks up the primary key 'note'
exists exists($options) or a primary key value: the builder's exists() of the query of those options, selecting 1; a limit and an offset are honoured ('limit' => 0, or an offset past the rows, is false) exists() and doesnt_exist()
all all($options), that is find('all', $options) get()
update_all, update update_all(['set' => [...], 'conditions' => ...]); a hash set also sets updated_at update([...]) on the query's where, order_by() and limit(); it sets updated_at too
delete_all, delete delete_all($options) delete() on the query's where, order_by() and limit()
create, insert create($attributes) builds a model: validations, callbacks, the model returned insert($rows) writes rows: no model, no validation, no callback; it returns true
upsert upsert($rows, $unique_by, $update) the same call
query query($sql, $values) runs raw SQL and returns the PDOStatement not the builder: new_query() starts one

Conditions

where() takes a column and a value, a column, an operator and a value, a hash, a list of conditions, or a closure:

or_where, where_not and or_where_not take the same forms. The rest of the family is where_in / where_not_in, where_null / where_not_null (a column or a list of columns), where_between / where_not_between (two values), where_between_columns, where_column (two columns), where_like / where_not_like, where_all / where_any / where_none, where_key / where_key_not (the primary key, one column) and where_raw, each with an or_ variant but where_key and where_key_not.

*The `_rawmethods send their SQL as written.**where_raw,or_where_raw,having_raw,or_having_raw, order_by_raw,group_by_raw,select_rawandfrom_raw(and theJOIN ...fragments ofjoins()) insert their SQL verbatim, with the values of its?markers bound, so it must never come from user input. A fragment that holds--or #is followed by a newline in the statement, so a line comment at its end (--, or#on MySQL and MariaDB) stops there and cannot cut off the clauses that follow it, which on a write include itsORDER BYandLIMIT. The legacy conditionsoption sends its SQL as given, so a comment at its end still cuts them off there. **A fragment that holds a statement terminator is refused at the call**: a;outside its strings, its quoted identifiers and its comments, as the database of the connection reads them, throwsActiveRecordException, which names the method. **So does a fragment that leaves a block comment open**, a/there with no/after it: SQLite runs the comment to the end of the statement, sowhere_raw('id > 0 / note')->order_by('id')->limit(1)->delete()deleted every row theWHEREmatched, and MySQL, MariaDB and Postgres refuse the statement. Block comments do not nest on MySQL, MariaDB and SQLite (/ / / is closed) and nest on Postgres (it is open there); MySQL's executable comments (/!,/M!) are open until their */`.

MySQL, MariaDB and SQLite would end the statement at such a ;, so the clauses that follow it would be cut off and a limited write would touch every row it matches; Postgres refuses the statement. A ; in a string (where_raw("note = 'a;b'")), an identifier, a comment or a bound value (where_raw('note = ?', ['a;b'])) is sent as written. The legacy conditions option refuses one too (see Hash conditions). The MySQL and MariaDB reading is that of their default sql_mode: a session with NO_BACKSLASH_ESCAPES reads 'C:\' as a whole string, so name != 'C:\' ; ' passes the check and the statement ends at its ; (the library sets no sql_mode). It also assumes a connection character set in which a \ byte is always a backslash (utf8mb4, utf8, latin1, ...): in GBK, Big5 or SJIS a \ byte can be the second byte of a character, so a fragment built for it can hide a ; from the check.

where_raw, or_where_raw, having_raw and or_having_raw refuse SQL that is empty or only whitespace at the call, and order_by_raw and group_by_raw refuse 0 too, which would name a column position that no statement has: the statement would otherwise leave the clause out, and a write could touch rows it was not asked to.

Columns and joins

Every method that takes a column (the wheres, select, order_by, group_by, having, pluck, value, the aggregates, the conditions of a join, and the keys of the values of update and insert) reads the name by one rule:

Selecting, ordering and paging

Eager loading

with() loads relationships along with the models, as the legacy include option does:

The names merge into the include tree. without('customer.invoices') removes by path (the parent stays loaded, and a name the query does not load takes nothing off and is not looked up), and with_only(...) replaces the tree. A relationship the model does not declare is refused at the call (RelationshipException), and so is a constraint on a relationship (with(['customer' => fn($query) => ...])), which is not supported. get(), first(), find() and the other terminals that return models load them; count(), exists(), value() and pluck() load nothing. As with the legacy include, a select() that leaves out the keys the relationship loads by fails (UndefinedPropertyException).

readonly() flags the models the query finds as readonly, as the legacy readonly option does, but not those loaded with them. It is not forwarded statically (see above).

when($value, $callback, $default = null) calls the callback when the value is truthy, and unless() when it is falsy: the shape of an optional filter ($default, when there is one, is called in the other case). A when() or unless() that runs neither is a filter that came out empty, and the writes refuse it: an update() or a delete() with no other where condition, and an insert() or an upsert(), which take no clause (see Writing); a read is unchanged. A Closure value is called first, and the callback is given the query and the value. If it returns a Query on the same model, that query goes on (a fork, for instance); any other return is ignored, where Eloquent uses any non-null result. tap($callback) calls back and returns the query.

Reading

Iterating over many rows

get() loads every row at once. To walk a big table, read it in pages: chunk() and chunk_by_id() pass each page to a callback, and lazy() and lazy_by_id() give the models one at a time as a generator. Each page is one statement (an ascending chunk_by_id() or lazy_by_id() without include_new_rows runs one max() probe first), and the with() relationships are loaded for each page, not for each row. cursor() reads the whole query as one statement, below.

Offset or keyset. chunk() and lazy() page by offset (LIMIT n OFFSET m). If the loop deletes the rows it reads, or updates a column the query filters on, the pages move under it and rows are skipped. chunk_by_id() and lazy_by_id() (and their _desc variants) page by key: each page is WHERE id > last ORDER BY id LIMIT n, so the loop may delete or update the rows it reads. Use them for that, and for big tables, where a large offset is slow. The key must be unique and must not change during the reading. Neither is detected: with a key that is not unique, the rows that share the last key of a page with rows after it are skipped silently.

Where it differs from Eloquent: these throw, at the call and before any statement.

The other differences are not refusals: include_new_rows is opt-in here, where Eloquent always reads new rows, and a stream (cursor(stream: true)) locks its connection on every adapter (see the busy rule below).

One statement: cursor(). cursor() runs the query once and gives the models one at a time as a generator, keyed from 0, hydrating each row only when it is reached.

The busy rule. While a stream is open its connection is busy, on every adapter. query(), a transaction start, commit() and a second stream on that connection throw ActiveRecord\ConnectionBusy. That includes what looks like a read: a lazy relationship load ($invoice->customer) and the first-use schema introspection of a model not yet used, both inside the loop. Load what the loop needs beforehand, or use the buffered cursor or lazy(). Other connections are not affected.

Shadowing. A model's own static method wins over the forwarded name (see Entry points), so a model that defines its own chunk() keeps it: call the builder's as Invoice::new_query()->chunk(...).

Soft delete. The builder does not go through consumer finder overrides, and neither do these methods. On a base model whose all() or find() hides soft-deleted rows, they return those rows too unless the query says so: Invoice::where_null('deleted_at')->chunk_by_id(...).

Aggregates

min, max, sum and avg (and average) read the column by its type, so the result is the same on MySQL, MariaDB and Postgres, and on SQLite for integer columns:

Column min, max, sum sum of no row avg
integer (a boolean too) an int when the exact value fits PHP_INT_MIN to PHP_INT_MAX, else its exact digits as a string 0 exact, a string
DECIMAL, NUMERIC the exact string, as the database returns it, its scale kept '0' exact, a string
floating (FLOAT, DOUBLE, REAL) a float 0.0 the database's AVG, a float
anything else: text, a date, a joined table's column, the alias of an expression the driver's value the driver's the driver's

The column is read by the name you aggregate. A query aggregated as a subquery (grouped, distinct or windowed, below) keeps its select there, so the alias of an expression named like a column of the model is what is aggregated, read by that column's type: select_raw('total_cents * 2 AS total_cents')->order_by('id')->limit(10)->sum('total_cents') is the int 144002. Any other alias gives the driver's value. A query aggregated in place drops its select, as Eloquent's aggregates do: select_raw('total_cents * 2 AS total_cents')->sum('total_cents') sums the column, 72001. min, max and avg of no row are null. An exact avg is the SUM divided by the COUNT in PHP, an exact long division rounded half up at the scale of the SUM plus 4 ('1.5000' for the integers 1 and 2, '12000.1667' above), where the databases' own AVG differ in type and scale.

Writing

Timestamps

save() sets the timestamps itself, as it always has, and the engine fills them in every other statement it writes:

Statement created_at updated_at
save() of a new record (create()) now, over a value you assigned now, over a value you assigned
save() of a record read (update_attributes()) not set now, over a value you assigned
INSERT: insert(), a direct Table::insert() when missing: now when missing: now
UPDATE: update(), update_all() with a hash set never when missing: now
UPSERT on the INSERT part, when missing: now when missing: now; also set on a conflict, unless the update list is empty
raw SQL: update_all() with a string set untouched untouched

save() goes through the model's set_timestamps(), which a model can override. That override governs save() only: insert(), update(), update_all() with a hash set, upsert() and a direct Table::insert() stamp the timestamps of every model, one that overrides set_timestamps() included, and only without_timestamps() suspends them.

A timestamp column is one whose attribute name is created_at or updated_at (a column named "created at" is one), and a value is missing when the data you give has none for that column, after name mapping (a given null is given; a key may be pre-quoted or qualified with the model's table). All the rows of an insert() or an upsert() take the same time. Model::without_timestamps($fn) suspends the rule for that model class while $fn runs, save() included, and returns $fn's result:

Suspensions nest, and the previous state is restored when $fn ends, also if it throws. It is for that class only: not for a subclass, a parent class or another model of the same table. A timestamp you give is still written, and a suspended upsert() does not add updated_at to the columns a conflict overwrites.

Where update_all() with a hash set must not touch updated_at, wrap the call in without_timestamps().

Debugging

The output is MySQL's.

get_bindings() lists the values in the order of the clauses (select, FROM, joins, WHERE, GROUP BY, HAVING, ORDER BY); the limit and the offset are written in the statement, not bound. to_raw_sql() is a debug aid, never for execution: it writes each value as the literal the adapter binds, so the text runs by hand as the bound statement does. A value the adapter binds as an integer is written bare (on SQLite, ints and bools), every other value as quoted text, as it is sent (on MySQL, MariaDB and Postgres an int is '5' and a bool '1'). So Postgres, run by hand, would refuse a bare 1 against a boolean column or a bare 5 against a text column, and SQLite compares a quoted '1' with an integer expression differently from the bound integer. null is NULL, and a DateTime is written as the builder binds it. It reads the ? markers as PDO does, outside strings and comments, and when they and the values do not match it throws an ActiveRecordException rather than write another statement than the one that runs.

Differences from Eloquent

Code ported from the Laravel documentation works by changing the method case, except for these deliberate differences (the sections above give the details):

Database notes

MySQL, MariaDB PostgreSQL SQLite
where_like, any case LIKE, as the column's collation decides ILIKE, on the column cast ::text, so a column of any type works LIKE, ASCII letters only
where_like, case-sensitive LIKE CONVERT(? USING utf8mb4) COLLATE utf8mb4_bin LIKE (::text too) GLOB, the pattern translated (% to *, _ to ?, GLOB metacharacters bracketed)
\ in a pattern escapes % and _ escapes % and _ a literal
in_random_order() RAND() RANDOM() RANDOM()
Aggregates exact exact; refuses SUM, AVG, MIN and MAX of a boolean (DatabaseException); MIN and MAX of a bytea need PostgreSQL 18; a numeric NaN or infinity stays the text 'NaN', 'Infinity' or '-Infinity' exact for integer columns; a DECIMAL column is stored as a REAL, so its aggregates are floats and the sum of no row is 0.0; an integer SUM beyond PHP_INT_MAX raises SQLite's integer overflow (DatabaseException)
having('alias', ...) accepted refused: write the aggregate with having_raw() accepted
A limited write native ORDER BY ... LIMIT the rows picked by primary key in a subquery; an order without a limit is ignored native ORDER BY ... LIMIT; an ORDER BY without a LIMIT is refused by SQLite (DatabaseException), as in update_all()

Examples

Rather than inline snippets, every major feature is shown as a runnable, self-contained example under examples/. Each creates its own SQLite database and runs with no setup:

Example Demonstrates
simple/ Basic CRUD (find/first/create/update/delete), the primary key create() fills in (an int, as find() gives it), tables without a primary key, the never-saved- and deleted-record update/delete guard, and convention overrides ($table_name, $primary_key)
finders/ Dynamic finders, the conditions/order/limit/offset/group/having/select options, last() (reversed order), first()/last() with an offset (the second / second-to-last record) or limit 0 (none), find_by_sql, static scopes, exists()/count() pk arguments as in find() (exists(0), count(1, 2, 3) = count([1, 2, 3])), a pk + conditions ANDed (find($id, ['conditions' => …]) → the record or RecordNotFound), find('first'|'last', <pks>) → the first/last of those pks ([2, 3] or 2, 3, ANDed with conditions), find('abc') → RecordNotFound (on Postgres without querying), update_all/delete_all with order + limit (emulated on Postgres with a primary-key subquery), delete_all()/update_all() arguments (a bare hash is the conditions; an unknown key beside set throws)
validations/ $validates_* macros, a custom validate(), the Errors object
relationships/ belongs_to (incl. class_name/foreign_key options), has_many, has_one, has_many … through, eager include, create_* builders, composite-key has_many with declared conditions, an OR in declared conditions stays scoped to the owner, a has_many keyed by a declared primary_key (lazy load, eager include and create_* agree, a declared limit applies per owner), a has_one with a declared offset (the child at that offset, lazy and eager)
callbacks/ Lifecycle hooks and halting a save
attributes/ Custom get_*/set_*, $alias_attribute, $attr_accessible (and strict mass assignment), $delegate, dirty tracking, tinyint(1) as an integer (Config::set_tinyint_as_boolean(false), MySQL), integers beyond PHP_INT_MAX, columns whose names are not attribute names ("first name" is first_name)
serialization/ to_json / to_xml / to_array with only/except/methods/include
upsert/ Model::upsert() — bulk insert-or-update with unique_by/update and managed timestamps
query_builder/ The fluent query builder: new_query() and static forwarding, the where family (operators, an $alias_attribute, a hash with a null in a list, where_like, closure groups, when), joins (join with a JoinClause closure, left_join, joins / left_joins by relationship), with (eager loading in two statements), the read terminals, exact aggregates (avg is a string), insert / update / delete with their timestamps and without_timestamps(), the refused empty where, to_sql / to_raw_sql
orders/ A fuller app combining validations, a callback, and relationships
inflection/ Table names derived from class names (Human → humans, Fireman → firemen, Complex → complexes, MatrixRow → matrix_rows), the has_many builders that follow, and $table_name as the escape hatch

See examples/README.md for the full index.

Contributing

Please refer to CONTRIBUTING.md for information on how to contribute to this fork.

License

MIT — see LICENSE.


All versions of php-activerecord with dependencies

PHP Build Version
Package Version
Requires php Version ^8.3
psr/log Version ^3.0
ext-pdo Version *
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package ristocloud-group/php-activerecord contains the following files

Loading the files please wait ...