PHPackages                             bephp/activerecord - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. bephp/activerecord

ActiveLibrary[Database &amp; ORM](/categories/database)

bephp/activerecord
==================

micro activerecord library in PHP(only 400 lines with comments), support chain calls and relations(HAS\_ONE, HAS\_MANY, BELONGS\_TO).

v2.2.1(8y ago)1202.1k19[1 issues](https://github.com/bephp/activerecord/issues)2MITPHPPHP &gt;=5.3.0

Since Sep 15Pushed 8y ago7 watchersCompare

[ Source](https://github.com/bephp/activerecord)[ Packagist](https://packagist.org/packages/bephp/activerecord)[ Docs](http://lloydzhou.github.io/activerecord/)[ RSS](/packages/bephp-activerecord/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (3)Versions (17)Used By (2)

activerecord
============

[](#activerecord)

[![Build Status](https://camo.githubusercontent.com/d8c8d2a63f52504fdd048df2ec21764d702b6474db2dfa0668fe8446e054fe5d/68747470733a2f2f7472617669732d63692e6f72672f62657068702f6163746976657265636f72642e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/bephp/activerecord)[![Coverage Status](https://camo.githubusercontent.com/e6839ad0dbe327ace8783b300705c76a671c896015164075dc32c0137bd90eb5/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f62657068702f6163746976657265636f72642f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/bephp/activerecord?branch=master)[![Latest Stable Version](https://camo.githubusercontent.com/f809596aa0fa7cce36d43c6eaa950e42d52170a4b9d58442dfe76951cd8d462a/68747470733a2f2f706f7365722e707567782e6f72672f62657068702f6163746976657265636f72642f762f737461626c65)](https://packagist.org/packages/bephp/activerecord) [![Total Downloads](https://camo.githubusercontent.com/95b639aa1ed8e54b6217e60b3a775d734fe6465734289e1f942fe450d69ed8f5/68747470733a2f2f706f7365722e707567782e6f72672f62657068702f6163746976657265636f72642f646f776e6c6f616473)](https://packagist.org/packages/bephp/activerecord) [![Latest Unstable Version](https://camo.githubusercontent.com/3438ef65bb5976d4d9f2a112253b99e247876eff7d16d6caf18aed70a3066fb1/68747470733a2f2f706f7365722e707567782e6f72672f62657068702f6163746976657265636f72642f762f756e737461626c65)](https://packagist.org/packages/bephp/activerecord) [![License](https://camo.githubusercontent.com/0d820b4dd9967c2907e263542cb4b056b896d1027d7226e327cf5b483eb40a48/68747470733a2f2f706f7365722e707567782e6f72672f62657068702f6163746976657265636f72642f6c6963656e7365)](https://packagist.org/packages/bephp/activerecord)

micro activerecord library in PHP(only 400 lines with comments), support chain calls and relations(HAS\_ONE, HAS\_MANY, BELONGS\_TO).

> [中文版](https://github.com/bephp/activerecord/blob/master/README.zh-CN.md).

Documentation
-------------

[](#documentation)

[Documentation](https://bephp.github.io/activerecord/)

API Reference
-------------

[](#api-reference)

### CRUD functions

[](#crud-functions)

#### setDb(\\PDO $db)

[](#setdbpdo--db)

set the DB connection.

```
ActiveRecord::setDb(new PDO('sqlite:test.db'));

```

#### insert() : boolean|\\ActiveRecord

[](#insert--booleanactiverecord)

function to build insert SQL, and insert current record into database. if insert success return current object, other wise return false.

```
$user = new User();
$user->name = 'demo';
$user->password = md5('demo');
$user->insert();

```

#### find(integer $id = null) : boolean|\\ActiveRecord

[](#findinteger--id--null--booleanactiverecord)

function to find one record and assign in to current object. If call this function using $id param, will find record by using this id. If not set, just find the first record in database. if find record, assign in to current object and return it, other wise return "false".

```
$user->notnull('id')->orderby('id desc')->find();

```

#### findAll() : array

[](#findall--array)

function to find all records in database. return array of ActiveRecord

```
$user->findAll();

```

#### update() : boolean|\\ActiveRecord

[](#update--booleanactiverecord)

function to build update SQL, and update current record in database, just write the dirty data into database. if update success return current object, other wise return false.

```
$user->notnull('id')->orderby('id desc')->find();
$user->email = 'test@example.com';
$user->update();

```

#### delete() : boolean

[](#delete--boolean)

function to delete current record in database.

#### reset() : \\ActiveRecord

[](#reset--activerecord)

function to reset the $params and $sqlExpressions. return $this, can using chain method calls.

#### dirty(array $dirty = array()) : \\ActiveRecord

[](#dirtyarray--dirty--array--activerecord)

function to SET or RESET the dirty data. The dirty data will be set, or empty array to reset the dirty data.

### SQL part functions

[](#sql-part-functions)

#### select()

[](#select)

function to set the select columns.

```
$user->select('id', 'name')->find();

```

#### from()

[](#from)

function to set the table to find record

```
$user->select('id', 'name')->from('user')->find();

```

#### join()

[](#join)

function to set the table to find record

```
$user->join('contact', 'contact.user_id = user.id')->find();

```

#### where()

[](#where)

function to set where conditions

```
$user->where('id=1 AND name="demo"')->find();

```

#### group()/groupby()

[](#groupgroupby)

```
$user->select('count(1) as count')->groupby('name')->findAll();

```

#### order()/orderby()

[](#orderorderby)

```
$user->orderby('name DESC')->find();

```

#### limit()

[](#limit)

```
$user->orderby('name DESC')->limit(0, 1)->find();

```

### WHERE conditions

[](#where-conditions)

#### equal()/eq()

[](#equaleq)

```
$user->eq('id', 1)->find();

```

#### notequal()/ne()

[](#notequalne)

```
$user->ne('id', 1)->find();

```

#### greaterthan()/gt()

[](#greaterthangt)

```
$user->gt('id', 1)->find();

```

#### lessthan()/lt()

[](#lessthanlt)

```
$user->lt('id', 1)->find();

```

#### greaterthanorequal()/ge()/gte()

[](#greaterthanorequalgegte)

```
$user->ge('id', 1)->find();

```

#### lessthanorequal()/le()/lte()

[](#lessthanorequallelte)

```
$user->le('id', 1)->find();

```

#### like()

[](#like)

```
$user->like('name', 'de')->find();

```

#### in()

[](#in)

```
$user->in('id', [1, 2])->find();

```

#### notin()

[](#notin)

```
$user->notin('id', [1,3])->find();

```

#### isnull()

[](#isnull)

```
$user->isnull('id')->find();

```

#### isnotnull()/notnull()

[](#isnotnullnotnull)

```
$user->isnotnull('id')->find();

```

Install
-------

[](#install)

```
composer require bephp/activerecord

```

There's one [Blog demo](https://github.com/bephp/blog), work with [Router](https://github.com/bephp/router) and [MicoTpl](https://github.com/bephp/microtpl).

Demo
----

[](#demo)

### Include base class ActiveRecord

[](#include-base-class-activerecord)

```
include "ActiveRecord.php";
```

### Define Class

[](#define-class)

```
class User extends ActiveRecord{
	public $table = 'user';
	public $primaryKey = 'id';
	public $relations = array(
		'contacts' => array(self::HAS_MANY, 'Contact', 'user_id'),
		'contact' => array(self::HAS_ONE, 'Contact', 'user_id'),
	);
}
class Contact extends ActiveRecord{
	public $table = 'contact';
	public $primaryKey = 'id';
	public $relations = array(
		'user' => array(self::BELONGS_TO, 'User', 'user_id'),
		'user_with_backref' => array(self::BELONGS_TO, 'User', 'user_id', array(), 'contact'),
        // using 5th param to define backref
	);
}
```

### Init data

[](#init-data)

```
ActiveRecord::setDb(new PDO('sqlite:test.db'));
ActiveRecord::execute("CREATE TABLE IF NOT EXISTS user (
                                id INTEGER PRIMARY KEY,
                                name TEXT,
                                password TEXT
                        );");
ActiveRecord::execute("CREATE TABLE IF NOT EXISTS contact (
                                id INTEGER PRIMARY KEY,
                                user_id INTEGER,
                                email TEXT,
                                address TEXT
                        );");
```

### Insert one User into database.

[](#insert-one-user-into-database)

```
$user = new User();
$user->name = 'demo';
$user->password = md5('demo');
var_dump($user->insert());
```

### Insert one Contact belongs the current user.

[](#insert-one-contact-belongs-the-current-user)

```
$contact = new Contact();
$contact->address = 'test';
$contact->email = 'test1234456@domain.com';
$contact->user_id = $user->id;
var_dump($contact->insert());
```

### Example to using relations

[](#example-to-using-relations)

```
$user = new User();
// find one user
var_dump($user->notnull('id')->orderby('id desc')->find());
echo "\nContact of User # {$user->id}\n";
// get contacts by using relation:
//   'contacts' => array(self::HAS_MANY, 'Contact', 'user_id'),
var_dump($user->contacts);

$contact = new Contact();
// find one contact
var_dump($contact->find());
// get user by using relation:
//    'user' => array(self::BELONGS_TO, 'User', 'user_id'),
var_dump($contact->user);
```

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity34

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 93.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~69 days

Recently: every ~165 days

Total

14

Last Release

3000d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5fe53a9780d36da291ceab6e1741680db86d0b40198cae9435c12044abfefabd?d=identicon)[lloydzhou](/maintainers/lloydzhou)

---

Top Contributors

[![lloydzhou](https://avatars.githubusercontent.com/u/1826685?v=4)](https://github.com/lloydzhou "lloydzhou (69 commits)")[![victorruan](https://avatars.githubusercontent.com/u/6701576?v=4)](https://github.com/victorruan "victorruan (3 commits)")[![Shangshj](https://avatars.githubusercontent.com/u/4253787?v=4)](https://github.com/Shangshj "Shangshj (2 commits)")

---

Tags

microdatabaseormpdoactiverecordrelation

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/bephp-activerecord/health.svg)

```
[![Health](https://phpackages.com/badges/bephp-activerecord/health.svg)](https://phpackages.com/packages/bephp-activerecord)
```

###  Alternatives

[flightphp/active-record

Micro Active Record library in PHP, support chain calls, events, and relations.

163.0k](/packages/flightphp-active-record)[tommyknocker/pdo-database-class

Framework-agnostic PHP database library with unified API for MySQL, MariaDB, PostgreSQL, SQLite, MSSQL, and Oracle. Query Builder, caching, sharding, window functions, CTEs, JSON, migrations, ActiveRecord, CLI tools, AI-powered analysis. Zero external dependencies.

845.7k](/packages/tommyknocker-pdo-database-class)[kumbia/activerecord

Fast ActiveRecord

261.6k](/packages/kumbia-activerecord)[icanboogie/activerecord

ActiveRecord Object-relational mapping

135.0k3](/packages/icanboogie-activerecord)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
