{"id":14972149,"url":"https://github.com/greg-md/php-orm","last_synced_at":"2025-10-26T18:31:39.742Z","repository":{"id":62512582,"uuid":"66441719","full_name":"greg-md/php-orm","owner":"greg-md","description":"A lightweight but powerful ORM(Object-Relational Mapping) library for PHP.","archived":false,"fork":false,"pushed_at":"2019-07-24T08:14:57.000Z","size":979,"stargazers_count":22,"open_issues_count":1,"forks_count":2,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-01-31T22:11:39.459Z","etag":null,"topics":["activerecord","big-data","greg-md","greg-php","intellisense","migrations","mssql","mysql","oracle","orm","php","php-orm","postgresql","query-builder","sqlite","web-artisans"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/greg-md.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-08-24T07:32:01.000Z","updated_at":"2024-11-26T02:56:17.000Z","dependencies_parsed_at":"2022-11-02T13:02:20.092Z","dependency_job_id":null,"html_url":"https://github.com/greg-md/php-orm","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/greg-md%2Fphp-orm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/greg-md%2Fphp-orm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/greg-md%2Fphp-orm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/greg-md%2Fphp-orm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/greg-md","download_url":"https://codeload.github.com/greg-md/php-orm/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":238386067,"owners_count":19463289,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["activerecord","big-data","greg-md","greg-php","intellisense","migrations","mssql","mysql","oracle","orm","php","php-orm","postgresql","query-builder","sqlite","web-artisans"],"created_at":"2024-09-24T13:46:27.594Z","updated_at":"2025-10-26T18:31:34.313Z","avatar_url":"https://github.com/greg-md.png","language":"PHP","readme":"# Greg ORM\n\n[![StyleCI](https://styleci.io/repos/66441719/shield?style=flat)](https://styleci.io/repos/66441719)\n[![Build Status](https://travis-ci.org/greg-md/php-orm.svg)](https://travis-ci.org/greg-md/php-orm)\n[![Total Downloads](https://poser.pugx.org/greg-md/php-orm/d/total.svg)](https://packagist.org/packages/greg-md/php-orm)\n[![Latest Stable Version](https://poser.pugx.org/greg-md/php-orm/v/stable.svg)](https://packagist.org/packages/greg-md/php-orm)\n[![Latest Unstable Version](https://poser.pugx.org/greg-md/php-orm/v/unstable.svg)](https://packagist.org/packages/greg-md/php-orm)\n[![License](https://poser.pugx.org/greg-md/php-orm/license.svg)](https://packagist.org/packages/greg-md/php-orm)\n\nA lightweight but powerful ORM(Object-Relational Mapping) library for PHP.\n\n[Gest Started](#get-started) with establishing a [Database Connection](#database-connection---quick-start),\ncreate an [Active Record Model](#active-record-model---quick-start) of a database table\nand write your first queries using the [Query Builder](#query-builder---quick-start).\n\n# Why use Greg ORM?\n\nYou can read about it in the next article: _pending_ \n\n# Get Started\n\n* [Requirements](#requirements)\n* [Installation](#installation)\n* [Supported Drivers](#supported-drivers)\n* [Database Connection - Quick Start](#database-connection---quick-start)\n* [Query Builder - Quick Start](#query-builder---quick-start)\n* [Active Record Model - Quick Start](#active-record-model---quick-start)\n\n## Requirements\n\n* PHP Version `^7.1`\n\n## Installation\n\nYou can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):\n\n`composer require greg-md/php-orm`\n\n## Supported Drivers\n\n- **MySQL**\n- **SQLite**\n\nIn progress:\n\n- MS SQL\n- PostgreSQL\n- Oracle\n\n## Database Connection - Quick Start\n\nThere are two ways of creating a database connection:\n\n1. Instantiate a database connection for a specific driver;\n2. Instantiate a connection manager to store multiple database connections.\n\n\u003e The connection manager implements the same connection strategy.\n\u003e This means that you can define a connection to act like it.\n\nIn the next example we will use a connection manager to store multiple connections of different drivers.\n\n```php\n// Instantiate a Connection Manager\n$manager = new \\Greg\\Orm\\Connection\\ConnectionManager();\n\n// Register a MySQL connection\n$manager-\u003eregister('mysql_connection', function() {\n    return new \\Greg\\Orm\\Connection\\MysqlConnection(\n        new \\Greg\\Orm\\Connection\\Pdo('mysql:dbname=example_db;host=127.0.0.1', 'john', 'doe')\n    );\n});\n\n// Register a SQLite connection\n$manager-\u003eregister('sqlite_connection', function() {\n    return new \\Greg\\Orm\\Connection\\SqliteConnection(\n        new \\Greg\\Orm\\Connection\\Pdo('sqlite:/var/db/example_db.sqlite')\n    );\n});\n\n// Make the manager to act as \"mysql_connection\"\n$manager-\u003eactAs('mysql_connection');\n```\n\nNow you can work with this manager:\n\n```php\n// Fetch a statement from \"sqlite_connection\"\n$manager-\u003econnection('sqlite_connection')\n    -\u003eselect()\n    -\u003efrom('Table')\n    -\u003efetchAll();\n\n// Fetch a statement from mysql_connection, which is used by default\n$manager\n    -\u003eselect()\n    -\u003efrom('Table')\n    -\u003efetchAll();\n```\n\nFull documentation can be found [here](docs/DatabaseConnection.md).\n\n## Active Record Model - Quick Start\n\nThe Active Record Model represents a table schema, an entity or a collection of entities of that table,\nintegrated with the Query Builder to speed up your coding process.\n\nLet's say you have `Users` table:\n\n```sql\nCREATE TABLE `Users` (\n  `Id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n  `Email` VARCHAR(255) NOT NULL,\n  `Password` VARCHAR(32) NOT NULL,\n  `SSN` VARCHAR(32) NULL,\n  `FirstName` VARCHAR(50) NULL,\n  `LastName` VARCHAR(50) NULL,\n  `Active` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1',\n  PRIMARY KEY (`Id`),\n  UNIQUE (`Email`),\n  UNIQUE (`SSN`),\n  KEY (`Password`),\n  KEY (`FirstName`),\n  KEY (`LastName`),\n  KEY (`Active`)\n);\n```\n\nLet's create the model for that table and configure it:\n\n```php\nclass UsersModel extends \\Greg\\Orm\\Model\n{\n    // Define table alias. (optional)\n    protected $alias = 'u';\n\n    // Cast columns. (optional)\n    protected $casts = [\n        'Active' =\u003e 'boolean',\n    ];\n\n    // Table name (required)\n    public function name(): string\n    {\n        return 'Users';\n    }\n\n    // Create abstract attribute \"FullName\". (optional)\n    public function getFullNameAttribute(): string\n    {\n        return implode(' ', array_filter([$this['FirstName'], $this['LastName']]));\n    }\n\n    // Change \"SSN\" attribute. (optional)\n    public function getSSNAttribute(): string\n    {\n        // Display only last 3 digits of the SSN.\n        return str_repeat('*', 6) . substr($this['SSN'], -3, 3);\n    }\n\n    // Extend SQL Builder. (optional)\n    public function whereIsNoFullName()\n    {\n        $this-\u003ewhereIsNull('FirstName')-\u003ewhereIsNull('LastName');\n\n        return $this;\n    }\n}\n```\n\nNow, let's instantiate that model. The only thing you need is a [Database Connection](#database-connection---quick-start):\n\n```php\n// Initialize the model.\n$usersModel = new UsersModel($connection);\n```\n\n#### Working with table schema\n\n```php\n// Display table name.\nprint_r($usersModel-\u003ename()); // result: Users\n\n// Display auto-increment column.\nprint_r($usersModel-\u003eautoIncrement()); // result: Id\n\n// Display primary keys.\nprint_r($usersModel-\u003eprimary()); // result: ['Id']\n\n// Display all unique keys.\nprint_r($usersModel-\u003eunique()); // result: [['Email'], ['SSN']]\n```\n\n#### Working with a single row\n\n```php\n// Create a user.\n$user = $usersModel-\u003ecreate([\n    'Email' =\u003e 'john@doe.com',\n    'Password' =\u003e password_hash('secret'),\n    'SSN' =\u003e '123456789',\n    'FirstName' =\u003e 'John',\n    'LastName' =\u003e 'Doe',\n]);\n\n// Display user email.\nprint_r($user['Email']); // result: john@doe.com\n\n// Display user full name.\nprint_r($user['FullName']); // result: John Doe\n\nprint_r($user['SSN']); // result: ******789\n\n// Display if user is active.\nprint_r($user['Active']); // result: true\n\n// Display user's primary keys.\nprint_r($user-\u003egetPrimary()); // result: ['Id' =\u003e 1]\n```\n\n#### Working with a row set\n\n```php\n// Create some users.\n$usersModel-\u003ecreate([\n   'Email' =\u003e 'john@doe.com',\n   'Password' =\u003e password_hash('secret'),\n   'Active' =\u003e true,\n]);\n\n$usersModel-\u003ecreate([\n   'Email' =\u003e 'matt@damon.com',\n   'Password' =\u003e password_hash('secret'),\n   'Active' =\u003e false,\n]);\n\n$usersModel-\u003ecreate([\n   'Email' =\u003e 'josh@barro.com',\n   'Password' =\u003e password_hash('secret'),\n   'Active' =\u003e false,\n]);\n\n// Fetch all inactive users from database.\n$inactiveUsers = $usersModel-\u003ewhereIsNot('Active')-\u003efetchAll();\n\n// Display users count.\nprint_r($inactiveUsers-\u003ecount()); // result: 2\n\n// Display users emails.\nprint_r($inactiveUsers-\u003eget('Email')); // result: ['matt@damon.com', 'josh@barro.com']\n\n// Activate all users in the row set.\n$inactiveUsers-\u003eset('Active', true)-\u003esave();\n\nprint_r($inactiveUsers[0]['Active']); // result: true\nprint_r($inactiveUsers[1]['Active']); // result: true\n```\n\n#### Working with Query Builder\n\nSelect users that doesn't have first and last names.\n\n```php\n$users = $usersModel\n    -\u003ewhereIsNoFullName()\n    -\u003eorderAsc('Id')\n    -\u003efetchAll();\n```\n\nUpdate an user:\n\n```php\n$usersModel\n    -\u003ewhere('Id', 10)\n    -\u003eupdate(['Email' =\u003e 'foo@bar.com']);\n```\n\nFull documentation can be found [here](docs/ActiveRecordModel.md).\n\n## Query Builder - Quick Start\n\nThe Query Builder provides an elegant way of creating SQL statements and clauses on different levels of complexity.\n\nYou can easily instantiate a Query Builder with a [Database Connection](#database-connection---quick-start).\n\nLet's say you have `Students` table.\n\nFind students names that lives in Chisinau and were born in 1990:\n\n```php\n$students = $connection-\u003eselect()\n    -\u003ecolumns('Id', 'Name')\n    -\u003efrom('Students')\n    -\u003ewhere('City', 'Chisinau')\n    -\u003ewhereYear('Birthday', 1990)\n    -\u003efetchAll();\n```\n\nUpdate the grade of a student:\n\n```php\n$connection-\u003eupdate()\n    -\u003etable('Students')\n    -\u003eset('Grade', 1400)\n    -\u003ewhere('Id', 10)\n    -\u003eexecute();\n```\n\nDelete students that were not admitted in the current year:\n\n```php\n$connection-\u003edelete()\n    -\u003efrom('Students')\n    -\u003ewhereIsNot('Admitted')\n    -\u003eexecute();\n```\n\nAdd a new student:\n\n```php\n$query = $connection-\u003einsert()\n    -\u003einto('Students')\n    -\u003edata(['Name' =\u003e 'John Doe', 'Year' =\u003e 2017])\n    -\u003eexecute();\n```\n\nFull documentation can be found [here](docs/QueryBuilder.md).\n\n# Documentation\n\n* [Database Connection](docs/DatabaseConnection.md)\n* [Active Record Model](docs/ActiveRecordModel.md)\n* [Query Builder](docs/QueryBuilder.md)\n* **Migrations** are under construction, but you can use [Phinx](https://phinx.org/) in the meantime.\n\n# License\n\nMIT © [Grigorii Duca](http://greg.md)\n\n# _Huuuge Quote_\n\n![I fear not the man who has practiced 10,000 programming languages once, but I fear the man who has practiced one programming language 10,000 times. \u0026copy; #horrorsquad](http://greg.md/huuuge-quote-fb.jpg)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgreg-md%2Fphp-orm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgreg-md%2Fphp-orm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgreg-md%2Fphp-orm/lists"}