PHP code example of ristocloud-group / php-activerecord

1. Go to this page and download the library: Download ristocloud-group/php-activerecord library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ristocloud-group / php-activerecord example snippets


ActiveRecord\Config::initialize(function (ActiveRecord\Config $cfg) {
    $cfg->set_connections([
        'development' => 'mysql://username:password@localhost/development_database_name',
        'test' => 'mysql://username:password@localhost/test_database_name',
        'production' => 'mysql://username:password@localhost/production_database_name',
    ]);
});

$cfg = ActiveRecord\Config::instance();
$cfg->set_connections([
    'development' => 'mysql://username:password@localhost/development_database_name',
    'test' => 'mysql://username:password@localhost/test_database_name',
    'production' => 'mysql://username:password@localhost/production_database_name',
]);

$cfg->set_connections([
    'development' => 'mysql://username:password@localhost/database_name?charset=utf8mb4',
    // password is "p@ss:word", percent-encoded because of decode=true
    'production' => 'mysql://username:p%40ss%[email protected]:3307/database_name?charset=utf8mb4&decode=true',
]);

ActiveRecord\Config::initialize(function (ActiveRecord\Config $cfg) {
    $cfg->set_default_connection('production'); // 'development', 'test', or 'production'
});

ActiveRecord\Config::initialize(function (ActiveRecord\Config $cfg) {
    $cfg->set_strict_mass_assignment(true);
});

ActiveRecord\Config::initialize(function (ActiveRecord\Config $cfg) {
    $cfg->set_tinyint_as_boolean(false);
});

$cfg->set_cache('memcache://localhost:11211', ['expire' => 120, 'namespace' => 'my_app']);

$cfg->set_cache('file:///var/tmp/php-activerecord-cache');

$cfg->set_cache('redis://localhost:6379/0', ['expire' => 120, 'namespace' => 'my_app']);

$cfg->set_cache('redis://user:[email protected]:6379/0?read_write_timeout=2', [
    'namespace' => 'my_app',
]);

$invoices = Invoice::where('status', 'open')
    ->where_in('customer_id', [1, 2])
    ->where('total_cents', '>=', 10000)
    ->order_by_desc('issued_on')
    ->limit(10)
    ->get();

foreach ($invoices as $invoice) {
    echo $invoice->number, "\n";
}

$open = Invoice::where('status', 'open')->order_by('id');
$first_two = $open->clone()->limit(2)->get();
$all_open = $open->get();                       // the limit was set on the clone

Invoice::where('status', 'open');                               // status = ?
Invoice::where('total_cents', '>', 10000);                      // total_cents > ?
Invoice::where(['status' => 'open', 'customer_id' => [1, 2]]);  // status = ? AND customer_id IN(?,?)
Invoice::where([['total_cents', '>', 5000], ['status', 'open']]);
Invoice::where('status', 'open')
    ->where(fn(ActiveRecord\Query $query) => $query->where('note', 'rush')->or_where('total_cents', '>=', 20000));
// WHERE status = ? AND (note = ? OR total_cents >= ?)

Invoice::join('customers', 'customers.id', '=', 'invoices.customer_id')
    ->where('customers.country', 'IT')
    ->where('id', '>', 1)                                // `invoices`.`id` > ?
    ->get();

Invoice::left_join('customers', fn(ActiveRecord\JoinClause $join) => $join
        ->on('customers.id', '=', 'invoices.customer_id')
        ->where('customers.country', 'DE'))
    ->select('invoices.*', 'customers.name as customer_name')
    ->get();                                             // customer_name is null where there is no German customer

Invoice::joins('customer')->where('customers.country', 'DE')->get();   // by relationship name
Customer::left_joins('invoices')->where_null('invoices.id')->get();    // the customers without an invoice

Invoice::select('number', 'total_cents as cents')->get();             // "column as alias" names the attribute
Invoice::select('customer_id')->select_raw('SUM(total_cents) AS total')
    ->group_by('customer_id')->having_raw('SUM(total_cents) > ?', [22000])->get();
Invoice::order_by('status')->order_by_desc('issued_on')->limit(10)->offset(20)->get();
Invoice::order_by('id')->for_page(3, 25)->get();                      // rows 51 to 75

Invoice::with('customer')->get();                      // two statements, however many invoices there are
Invoice::with('customer.invoices')->get();             // dot notation: each customer's invoices as well
Invoice::with(['customer' => ['invoices']])->get();    // or as the 

$invoices = Invoice::when($status, fn(ActiveRecord\Query $query, mixed $status) => $query->where('status', $status))->get();

Invoice::where('status', 'open')->get();                    // an array of models
Invoice::where('number', 'INV-004')->first();               // a model, or null
Invoice::where('number', 'INV-004')->first_or_fail();       // a model, or RecordNotFound
Invoice::where('number', 'INV-004')->sole();                // the one model: RecordNotFound, or MultipleRecordsFound
Invoice::new_query()->find(3);                              // a model, or null
Invoice::new_query()->find([1, 3, 99]);                     // the models found: 1 and 3
Invoice::where('number', 'INV-003')->value('total_cents');  // 20000
Invoice::where('status', 'open')->pluck('number');          // ['INV-002', 'INV-005', 'INV-006']
Invoice::order_by('id')->pluck('total_cents', 'number');    // ['INV-001' => 12000, ...]
Invoice::where('status', 'void')->exists();                 // true
Invoice::where('status', 'open')->count();                  // 3

Customer::where('active', 1)->chunk(100, function (array $customers, int $page): void {
    foreach ($customers as $customer) {
        // ...
    }
});

foreach (Customer::where('active', 1)->lazy(500) as $customer) {
    // ...
}

Invoice::where('status', 'open')->chunk_by_id(500, function (array $invoices): void {
    foreach ($invoices as $invoice) {
        $invoice->delete();                         // no row is skipped
    }
});

foreach (Invoice::where('status', 'open')->lazy_by_id(500) as $invoice) {
    // ...
}

Invoice::new_query()->chunk_by_id_desc(500, $callback);   // highest id first
Invoice::new_query()->lazy_by_id_desc(500);               // the same, as a generator

Invoice::new_query()->chunk_by_id(500, $callback, column: 'number');              // another unique column
Invoice::new_query()->chunk_by_id(500, $callback, column: 'id', alias: 'inv_id'); // key selected as `inv_id`
Invoice::new_query()->chunk_by_id(500, $callback, 

foreach (Customer::where('active', 1)->cursor() as $customer) {
    // ...
}

foreach (Invoice::new_query()->cursor(stream: true) as $invoice) {   // rows read from the server one at a time
    // no other statement on this connection in here
}

foreach (Invoice::new_query()->cursor(stream: true) as $invoice) {
    $invoice->customer;       // throws ConnectionBusy if not loaded yet
}

Invoice::sum('total_cents');                           // 72001
Invoice::min('total_cents');                           // 5000
Invoice::avg('total_cents');                           // '12000.1667', a string
Invoice::where('status', 'lost')->avg('total_cents');  // null

Invoice::new_query()->insert([                                          // true
    ['customer_id' => 4, 'number' => 'INV-007', 'status' => 'open', 'total_cents' => 1500, 'issued_on' => new DateTime('2026-04-01')],
    ['customer_id' => 4, 'number' => 'INV-008', 'status' => 'open', 'total_cents' => 2500, 'issued_on' => new DateTime('2026-04-02')],
]);
Invoice::where('customer_id', 4)->update(['status' => 'void']);         // 2: the rows written
Invoice::where('customer_id', 4)->order_by('id')->limit(5)->delete();   // 2
Invoice::new_query()->update(['note' => null]);                         // every row, because it says so

$invoice = Invoice::without_timestamps(fn() => Invoice::create(['customer_id' => 1, 'number' => 'INV-009', 'status' => 'open', 'total_cents' => 100, 'issued_on' => '2026-05-01']));

$query = Invoice::where('status', 'open')->where('total_cents', '>', 5000)->order_by_desc('issued_on')->limit(2);
$query->to_sql();        // SELECT * FROM `invoices` WHERE `status` = ? AND `total_cents` > ? ORDER BY `issued_on` DESC LIMIT 2
$query->get_bindings();  // ['open', 5000]
$query->to_raw_sql();    // SELECT * FROM `invoices` WHERE `status` = 'open' AND `total_cents` > '5000' ORDER BY `issued_on` DESC LIMIT 2
sh
php examples/simple/simple.php