{"id":36969672,"url":"https://github.com/jsnoriegam/pixie","last_synced_at":"2026-01-13T21:35:56.459Z","repository":{"id":57012682,"uuid":"79879131","full_name":"jsnoriegam/pixie","owner":"jsnoriegam","description":"Database query builder for PHP, framework agnostic, lightweight and expressive.","archived":false,"fork":true,"pushed_at":"2019-03-24T20:01:59.000Z","size":317,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-04-19T18:05:26.849Z","etag":null,"topics":["mysql","php","postgresql","query-builder","sqlite"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"skipperbent/pixie","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jsnoriegam.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":"2017-01-24T04:42:11.000Z","updated_at":"2019-03-09T20:56:41.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/jsnoriegam/pixie","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/jsnoriegam/pixie","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsnoriegam%2Fpixie","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsnoriegam%2Fpixie/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsnoriegam%2Fpixie/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsnoriegam%2Fpixie/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jsnoriegam","download_url":"https://codeload.github.com/jsnoriegam/pixie/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsnoriegam%2Fpixie/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28401046,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-13T14:36:09.778Z","status":"ssl_error","status_checked_at":"2026-01-13T14:35:19.697Z","response_time":56,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["mysql","php","postgresql","query-builder","sqlite"],"created_at":"2026-01-13T21:35:55.780Z","updated_at":"2026-01-13T21:35:56.449Z","avatar_url":"https://github.com/jsnoriegam.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Pixie Query Builder [![Build Status](https://travis-ci.org/jsnoriegam/pixie.svg?branch=master)](https://travis-ci.org/jsnoriegam/pixie)\nA lightweight, expressive, framework agnostic query builder for PHP it can also be referred as a Database Abstraction Layer. Pixie supports MySQL, SQLite and PostgreSQL and it takes care of query sanitization, table prefixing and many other things with a unified API. At least PHP 5.6 is required.\n\n## NOTE\nThis forked version aims to deploy pull-requests and fix bugs quicker.\n\nIt has some advanced features like:\n\n - Query Events\n - Nested Criteria\n - Sub Queries\n - Nested Queries\n - Multiple Database Connections.\n\nThe syntax is quite similar to Laravel's query builder.\n\n## Example\n```PHP\n// Make sure you have Composer's autoload file included\nrequire 'vendor/autoload.php';\n\n// Create a connection, once only.\n$config = array(\n            'driver'    =\u003e 'mysql', // Db driver\n            'host'      =\u003e 'localhost',\n            'database'  =\u003e 'your-database',\n            'username'  =\u003e 'root',\n            'password'  =\u003e 'your-password',\n            'charset'   =\u003e 'utf8', // Optional\n            'collation' =\u003e 'utf8_unicode_ci', // Optional\n            'prefix'    =\u003e 'cb_', // Table prefix, optional\n            'options'   =\u003e array( // PDO constructor options, optional\n                PDO::ATTR_TIMEOUT =\u003e 5,\n                PDO::ATTR_EMULATE_PREPARES =\u003e false,\n            ),\n        );\n\n$connection = new \\Pixie\\Connection($config);\n```\n\n**Simple Query:**\n\nThe query below returns the row where id = 3, null if no rows.\n```PHP\n$row = $qb-\u003etable('my_table')-\u003efind(3);\n```\n\n**Full Queries:**\n\n```PHP\n$query = $qb-\u003etable('my_table')-\u003ewhere('name', '=', 'Sana');\n\n// Get result\n$query-\u003eget();\n```\n\n**Query Events:**\n\nAfter the code below, every time a select query occurs on `users` table, it will add this where criteria, so banned users don't get access.\n\n```PHP\n$qb-\u003eregisterEvent('before-select', 'users', function($qb)\n{\n    $qb-\u003ewhere('status', '!=', 'banned');\n});\n```\n\n\nThere are many advanced options which are documented below. Sold? Let's install.\n\n## Installation\n\nNot yet\n\n## Full Usage API\n\n### Table of Contents\n\n - [Connection](#connection)\n    - [SQLite and PostgreSQL Config Sample](#sqlite-and-postgresql-config-sample)\n - [Query](#query)\n - [**Select**](#select)\n    - [Get Easily](#get-easily)\n    - [Multiple Selects](#multiple-selects)\n    - [Select Distinct](#select-distinct)\n    - [Get All](#get-all)\n    - [Get First Row](#get-first-row)\n    - [Get Rows Count](#get-rows-count)\n    - [Selects With Sub-Queries](#select-with-sub-queries)\n - [**Where**](#where)\n    - [Where In](#where-in)\n    - [Where Between](#where-between)\n    - [Where Null](#where-null)\n    - [Grouped Where](#grouped-where)\n - [Group By and Order By](#group-by-and-order-by)\n - [Having](#having)\n - [Limit and Offset](#limit-and-offset)\n - [Join](#join)\n    - [Multiple Join Criteria](#multiple-join-criteria)\n - [Raw Query](#raw-query)\n    - [Raw Expressions](#raw-expressions)\n - [**Insert**](#insert)\n    - [Batch Insert](#batch-insert)\n    - [Insert with ON DUPLICATE KEY statement](#insert-with-on-duplicate-key-statement)\n - [**Update**](#update)\n - [**Delete**](#delete)\n - [**Transactions**](#transactions)\n - [Get Built Query](#get-built-query)\n - [Sub Queries and Nested Queries](#sub-queries-and-nested-queries)\n - [Get PDO Instance](#get-pdo-instance)\n - [Fetch results as objects of specified class](#fetch-results-as-objects-of-specified-class)\n - [Query Events](#query-events)\n    - [Available Events](#available-events)\n    - [Registering Events](#registering-events)\n    - [Removing Events](#removing-events)\n    - [Some Use Cases](#some-use-cases)\n    - [Notes](#notes)\n\n___\n\n## Connection\nPixie supports three database drivers, MySQL, SQLite and PostgreSQL. You can specify the driver during connection and the associated configuration when creating a new connection. You can also create multiple connections, but you can use alias for only one connection at a time.;\n```PHP\n// Make sure you have Composer's autoload file included\nrequire 'vendor/autoload.php';\n\n$config = array(\n            'driver'    =\u003e 'mysql', // Db driver/adapter\n            'host'      =\u003e 'localhost',\n            'database'  =\u003e 'your-database',\n            'username'  =\u003e 'root',\n            'password'  =\u003e 'your-password',\n            'charset'   =\u003e 'utf8', // Optional\n            'collation' =\u003e 'utf8_unicode_ci', // Optional\n            'prefix'    =\u003e 'cb_', // Table prefix, optional\n        );\n\nnew \\Pixie\\Connection($config);\n\n//$connection here is optional, if not given it will always associate itself to the first connection, but it can be useful when you have multiple database connections.\n$qb = new \\Pixie\\QueryBuilder\\QueryBuilderHandler($connection);\n\n// Run query\n$query = $qb-\u003etable('my_table')-\u003ewhere('name', '=', 'Sana');\n```\n\n### SQLite and PostgreSQL Config Sample\n```PHP\n$connection = new \\Pixie\\Connection(array(\n        'driver'   =\u003e 'sqlite',\n        'database' =\u003e 'your-file.sqlite',\n        'prefix'   =\u003e 'cb_',\n));\n```\n\n```PHP\n$connection = new \\Pixie\\Connection(array(\n        'driver'   =\u003e 'pgsql',\n        'host'     =\u003e 'localhost',\n        'database' =\u003e 'your-database',\n        'username' =\u003e 'postgres',\n        'password' =\u003e 'your-password',\n        'charset'  =\u003e 'utf8',\n        'prefix'   =\u003e 'cb_',\n        'schema'   =\u003e 'public',\n));\n```\n\n## Query\nYou **must** use `table()` method before every query, except raw `query()`.\nTo select from multiple tables just pass an array.\n```PHP\n$qb-\u003etable(array('mytable1', 'mytable2'));\n```\n\n\n### Get Easily\nThe query below returns the (first) row where id = 3, null if no rows.\n```PHP\n$row = $qb-\u003etable('my_table')-\u003efind(3);\n```\nAccess your row like, `echo $row-\u003ename`. If your field name is not `id` then pass the field name as second parameter `$qb-\u003etable('my_table')-\u003efind(3, 'person_id');`.\n\nThe query below returns the all rows where name = 'Sana', null if no rows.\n```PHP\n$result = $qb-\u003etable('my_table')-\u003efindAll('name', 'Sana');\n```\n\n\n### Select\n```PHP\n$query = $qb-\u003etable('my_table')-\u003eselect('*');\n```\n\n#### Multiple Selects\n```PHP\n-\u003eselect(array('mytable.myfield1', 'mytable.myfield2', 'another_table.myfield3'));\n```\n\nUsing select method multiple times `select('a')-\u003eselect('b')` will also select `a` and `b`. Can be useful if you want to do conditional selects (within a PHP `if`).\n\n\n#### Select Distinct\n```PHP\n-\u003eselectDistinct(array('mytable.myfield1', 'mytable.myfield2'));\n```\n\n\n#### Get All\nReturn an array.\n```PHP\n$query = $qb-\u003etable('my_table')-\u003ewhere('name', '=', 'Sana');\n$result = $query-\u003eget();\n```\nYou can loop through it like:\n```PHP\nforeach ($result as $row) {\n    echo $row-\u003ename;\n}\n```\n\n#### Get First Row\n```PHP\n$query = $qb-\u003etable('my_table')-\u003ewhere('name', '=', 'Sana');\n$row = $query-\u003efirst();\n```\nReturns the first row, or null if there is no record. Using this method you can also make sure if a record exists. Access these like `echo $row-\u003ename`.\n\n\n#### Get Rows Count\n```PHP\n$query = $qb-\u003etable('my_table')-\u003ewhere('name', '=', 'Sana');\n$query-\u003ecount();\n```\n\n#### Select With Sub-Queries\n\n```PHP\n$subQuery1 = $this-\u003ebuilder-\u003etable('mail')-\u003eselect($this-\u003ebuilder-\u003eraw('COUNT(*)'));\n$subQuery2 = $this-\u003ebuilder-\u003etable('event_message')-\u003eselect($this-\u003ebuilder-\u003eraw('COUNT(*)'));\n\n$count = $this-\u003ebuilder-\u003eselect($this-\u003ebuilder-\u003esubQuery($subQuery1, 'row1'), $this-\u003ebuilder-\u003esubQuery($subQuery2, 'row2'))-\u003efirst();\n```\n\nWill produce the following query:\n\n```sql\nSELECT (SELECT COUNT(*) FROM `cb_mail`) as row1, (SELECT COUNT(*) FROM `cb_event_message`) as row2 LIMIT 1\n```\n\n### Where\nBasic syntax is `(fieldname, operator, value)`, if you give two parameters then `=` operator is assumed. So `where('name', 'usman')` and `where('name', '=', 'usman')` is the same.\n\n```PHP\n$qb-\u003etable('my_table')\n    -\u003ewhere('name', '=', 'usman')\n    -\u003ewhereNot('age', '\u003e', 25)\n    -\u003eorWhere('type', '=', 'admin')\n    -\u003eorWhereNot('description', 'LIKE', '%query%')\n    ;\n```\n\nUsing aliases:\n\n```PHP\n$qb-\u003etable(['my_table' =\u003e 'm'])\n    -\u003ewhere('m.name', '=', 'usman')\n    -\u003ewhereNot('m.age', '\u003e', 25)\n    -\u003eorWhere('m.type', '=', 'admin')\n    -\u003eorWhereNot('m.description', 'LIKE', '%query%')\n    -\u003eselect(['m.age' =\u003e 'my_age', 'm.type' =\u003e 'my_type'])\n    ;\n```\n\n\n#### Where In\n```PHP\n$qb-\u003etable('my_table')\n    -\u003ewhereIn('name', array('usman', 'sana'))\n    -\u003eorWhereIn('name', array('heera', 'dalim'));\n\n$qb-\u003etable('my_table')\n    -\u003ewhereNotIn('name', array('heera', 'dalim'))\n    -\u003eorWhereNotIn('name', array('usman', 'sana'));\n```\n\n#### Where Between\n```PHP\n$qb-\u003etable('my_table')\n    -\u003ewhereBetween('id', 10, 100)\n    -\u003eorWhereBetween('status', 5, 8);\n```\n\n#### Where Null\n```PHP\n$qb-\u003etable('my_table')\n    -\u003ewhereNull('modified')\n    -\u003eorWhereNull('field2')\n    -\u003ewhereNotNull('field3')\n    -\u003eorWhereNotNull('field4');\n```\n\n#### Grouped Where\nSometimes queries get complex, where you need grouped criteria, for example `WHERE age = 10 and (name like '%usman%' or description LIKE '%usman%')`.\n\nPixie allows you to do so, you can nest as many closures as you need, like below.\n```PHP\n$qb-\u003etable('my_table')\n            -\u003ewhere('my_table.age', 10)\n            -\u003ewhere(function($q)\n                {\n                    $q-\u003ewhere('name', 'LIKE', '%usman%');\n                    // You can provide a closure on these wheres too, to nest further.\n                    $q-\u003eorWhere('description', 'LIKE', '%usman%');\n                });\n```\n\n### Group By and Order By\n```PHP\n$query = $qb-\u003etable('my_table')-\u003egroupBy('age')-\u003eorderBy('created_at', 'ASC');\n```\n\n#### Multiple Group By\n```PHP\n-\u003egroupBy(array('mytable.myfield1', 'mytable.myfield2', 'another_table.myfield3'));\n\n-\u003eorderBy(array('mytable.myfield1', 'mytable.myfield2', 'another_table.myfield3'));\n```\n\nUsing `groupBy()` or `orderBy()` methods multiple times `groupBy('a')-\u003egroupBy('b')` will also group by first `a` and than `b`. Can be useful if you want to do conditional grouping (within a PHP `if`). Same applies to `orderBy()`.\n\n### Having\n```PHP\n-\u003ehaving('total_count', '\u003e', 2)\n-\u003eorHaving('type', '=', 'admin');\n```\n\n### Limit and Offset\n```PHP\n-\u003elimit(30);\n\n-\u003eoffset(10);\n```\n\n### Join\n```PHP\n$qb-\u003etable('my_table')\n    -\u003ejoin('another_table', 'another_table.person_id', '=', 'my_table.id')\n\n```\n\nAvailable methods,\n\n - join() or innerJoin\n - leftJoin()\n - rightJoin()\n\nIf you need `FULL OUTER` join or any other join, just pass it as 5th parameter of `join` method.\n```PHP\n-\u003ejoin('another_table', 'another_table.person_id', '=', 'my_table.id', 'FULL OUTER')\n```\n\nFor aliases use the same sintax of **select()** and **table()**\n```PHP\n$qb-\u003etable(['my_table' =\u003e 'm'])\n    -\u003ejoin(['another_table' =\u003e 'a'], 'a.person_id', '=', 'm.id')\n\n```\n*Only the first item on the array is used*\n\n#### Multiple Join Criteria\nIf you need more than one criterion to join a table then pass a closure as second parameter.\n\n```PHP\n-\u003ejoin('another_table', function($table)\n    {\n        $table-\u003eon('another_table.person_id', '=', 'my_table.id');\n        $table-\u003eon('another_table.person_id2', '=', 'my_table.id2');\n        $table-\u003eorOn('another_table.age', '\u003e', $qb-\u003eraw(1));\n    })\n```\n\n### Raw Query\nYou can always use raw queries if you need,\n```PHP\n$query = $qb-\u003equery('select * from cb_my_table where age = 12');\n\nvar_dump($query-\u003eget());\n```\n\nYou can also pass your bindings\n```PHP\n$qb-\u003equery('select * from cb_my_table where age = ? and name = ?', array(10, 'usman'));\n```\n\n#### Raw Expressions\n\nWhen you wrap an expression with `raw()` method, Pixie doesn't try to sanitize these.\n```PHP\n$qb-\u003etable('my_table')\n            -\u003eselect($qb-\u003eraw('count(cb_my_table.id) as tot'))\n            -\u003ewhere('value', '=', 'Ifrah')\n            -\u003ewhere($qb-\u003eraw('DATE(?)', 'now'))\n```\n\n\n___\n**NOTE:** Queries that run through `query()` method are not sanitized until you pass all values through bindings. Queries that run through `raw()` method are not sanitized either, you have to do it yourself. And of course these don't add table prefix too, but you can use the `addTablePrefix()` method.\n\n### Insert\n```PHP\n$data = array(\n    'name' =\u003e 'Sana',\n    'description' =\u003e 'Blah'\n);\n$insertId = $qb-\u003etable('my_table')-\u003einsert($data);\n```\n\n`insert()` method returns the insert id.\n\n#### Batch Insert\n```PHP\n$data = array(\n    array(\n        'name'        =\u003e 'Sana',\n        'description' =\u003e 'Blah'\n    ),\n    array(\n        'name'        =\u003e 'Usman',\n        'description' =\u003e 'Blah'\n    ),\n);\n$insertIds = $qb-\u003etable('my_table')-\u003einsert($data);\n```\n\nIn case of batch insert, it will return an array of insert ids.\n\n#### Insert with ON DUPLICATE KEY statement\n```PHP\n$data = array(\n    'name'    =\u003e 'Sana',\n    'counter' =\u003e 1\n);\n$dataUpdate = array(\n    'name'    =\u003e 'Sana',\n    'counter' =\u003e 2\n);\n$insertId = $qb-\u003etable('my_table')-\u003eonDuplicateKeyUpdate($dataUpdate)-\u003einsert($data);\n```\n\n### Update\n```PHP\n$data = array(\n    'name'        =\u003e 'Sana',\n    'description' =\u003e 'Blah'\n);\n\n$qb-\u003etable('my_table')-\u003ewhere('id', 5)-\u003eupdate($data);\n```\n\nWill update the name field to Sana and description field to Blah where id = 5.\n\n### Delete\n```PHP\n$qb-\u003etable('my_table')-\u003ewhere('id', '\u003e', 5)-\u003edelete();\n```\nWill delete all the rows where id is greater than 5.\n\n### Transactions\n\nPixie has the ability to run database \"transactions\", in which all database\nchanges are not saved until committed. That way, if something goes wrong or\ndifferently then you intend, the database changes are not saved and no changes\nare made.\n\nHere's a basic transaction:\n\n```PHP\n$qb-\u003etransaction(function ($qb2) {\n    $qb2-\u003etable('my_table')-\u003einsert(array(\n        'name' =\u003e 'Test',\n        'url' =\u003e 'example.com'\n    ));\n\n    $qb2-\u003etable('my_table')-\u003einsert(array(\n        'name' =\u003e 'Test2',\n        'url' =\u003e 'example.com'\n    ));\n});\n```\n\nIf this were to cause any errors (such as a duplicate name or some other such\nerror), neither data set would show up in the database. If not, the changes would\nbe successfully saved.\n\nIf you wish to manually commit or rollback your changes, you can use the\n`commit()` and `rollback()` methods accordingly:\n\n```PHP\n$qb-\u003etransaction(function (qb) {\n    $qb-\u003etable('my_table')-\u003einsert(array(/* data... */));\n\n    $qb-\u003ecommit(); // to commit the changes (data would be saved)\n    $qb-\u003erollback(); // to rollback the changes (data would be rejected)\n});\n```\n\n### Get Built Query\nSometimes you may need to get the query string, its possible.\n```PHP\n$query = $qb-\u003etable('my_table')-\u003ewhere('id', '=', 3);\n$queryObj = $query-\u003egetQuery();\n```\n`getQuery()` will return a query object, from this you can get sql, bindings or raw sql.\n\n\n```PHP\n$queryObj-\u003egetSql();\n// Returns: SELECT * FROM my_table where `id` = ?\n```\n```PHP\n$queryObj-\u003egetBindings();\n// Returns: array(3)\n```\n\n```PHP\n$queryObj-\u003egetRawSql();\n// Returns: SELECT * FROM my_table where `id` = 3\n```\n\n### Sub Queries and Nested Queries\nRarely but you may need to do sub queries or nested queries. Pixie is powerful enough to do this for you. You can create different query objects and use the `$qb-\u003esubQuery()` method.\n\n```PHP\n$subQuery = $qb-\u003etable('person_details')-\u003eselect('details')-\u003ewhere('person_id', '=', 3);\n\n\n$query = $qb-\u003etable('my_table')\n            -\u003eselect('my_table.*')\n            -\u003eselect($qb-\u003esubQuery($subQuery, 'table_alias1'));\n\n$nestedQuery = $qb-\u003etable($qb-\u003esubQuery($query, 'table_alias2'))-\u003eselect('*');\n$nestedQuery-\u003eget();\n```\n\nThis will produce a query like this:\n\n    SELECT * FROM (SELECT `cb_my_table`.*, (SELECT `details` FROM `cb_person_details` WHERE `person_id` = 3) as table_alias1 FROM `cb_my_table`) as table_alias2\n\n**NOTE:** Pixie doesn't use bindings for sub queries and nested queries. It quotes values with PDO's `quote()` method.\n\n### Get PDO Instance\nIf you need to get the PDO instance you can do so.\n\n```PHP\n$qb-\u003epdo();\n```\n\n### Fetch results as objects of specified class\nSimply call `asObject` query's method.\n\n```PHP\n$qb-\u003etable('my_table')-\u003easObject('SomeClass', array('ctor', 'args'))-\u003efirst();\n```\n\nFurthermore, you may fine-tune fetching mode by calling `setFetchMode` method.\n\n```PHP\n$qb-\u003etable('my_table')-\u003esetFetchMode(PDO::FETCH_COLUMN|PDO::FETCH_UNIQUE)-\u003eget();\n```\n\n### Query Events\nPixie comes with powerful query events to supercharge your application. These events are like database triggers, you can perform some actions when an event occurs, for example you can hook `after-delete` event of a table and delete related data from another table.\n\n#### Available Events\n\n - after-*\n - before-*\n - before-select\n - after-select\n - before-insert\n - after-insert\n - before-update\n - after-update\n - before-delete\n - after-delete\n\n#### Registering Events\n\n```PHP\n$qb-\u003eregisterEvent('before-select', 'users', function($qb)\n{\n    $qb-\u003ewhere('status', '!=', 'banned');\n});\n```\nNow every time a select query occurs on `users` table, it will add this where criteria, so banned users don't get access.\n\nThe syntax is `registerEvent('event type', 'table name', action in a closure)`.\n\nIf you want the event to be performed when **any table is being queried**, provide `':any'` as table name.\n\n**Other examples:**\n\nAfter inserting data into `my_table`, details will be inserted into another table\n```PHP\n$qb-\u003eregisterEvent('after-insert', 'my_table', function($queryBuilder, $insertId)\n{\n    $data = array('person_id' =\u003e $insertId, 'details' =\u003e 'Meh', 'age' =\u003e 5);\n    $queryBuilder-\u003etable('person_details')-\u003einsert($data);\n});\n```\n\nWhenever data is inserted into `person_details` table, set the timestamp field `created_at`, so we don't have to specify it everywhere:\n```PHP\n$qb-\u003eregisterEvent('after-insert', 'person_details', function($queryBuilder, $insertId)\n{\n    $queryBuilder-\u003etable('person_details')-\u003ewhere('id', $insertId)-\u003eupdate(array('created_at' =\u003e date('Y-m-d H:i:s')));\n});\n```\n\nAfter deleting from `my_table` delete the relations:\n```PHP\n$qb-\u003eregisterEvent('after-delete', 'my_table', function($queryBuilder, $queryObject)\n{\n    $bindings = $queryObject-\u003egetBindings();\n    $queryBuilder-\u003etable('person_details')-\u003ewhere('person_id', $binding[0])-\u003edelete();\n});\n```\n\n\n\nPixie passes the current instance of query builder as first parameter of your closure so you can build queries with this object, you can do anything like usual query builder (`QB`).\n\nIf something other than `null` is returned from the `before-*` query handler, the value will be result of execution and DB will not be actually queried (and thus, corresponding `after-*` handler will not be called either).\n\nOnly on `after-*` events you get three parameters: **first** is the query builder, **third** is the execution time as float and **the second** varies:\n\n - On `after-select` you get the `results` obtained from `select`.\n - On `after-insert` you get the insert id (or array of ids in case of batch insert)\n - On `after-delete` you get the [query object](#get-built-query) (same as what you get from `getQuery()`), from it you can get SQL and Bindings.\n - On `after-update` you get the [query object](#get-built-query) like `after-delete`.\n\n#### Removing Events\n```PHP\n$qb-\u003eremoveEvent('event-name', 'table-name');\n```\n\n#### Some Use Cases\n\nHere are some cases where Query Events can be extremely helpful:\n\n - Restrict banned users.\n - Get only `deleted = 0` records.\n - Implement caching of all queries.\n - Trigger user notification after every entry.\n - Delete relationship data after a delete query.\n - Insert relationship data after an insert query.\n - Keep records of modification after each update query.\n - Add/edit created_at and updated _at data after each entry.\n\n#### Notes\n - Query Events are set as per connection basis so multiple database connection don't create any problem, and creating new query builder instance preserves your events.\n - Query Events go recursively, for example after inserting into `table_a` your event inserts into `table_b`, now you can have another event registered with `table_b` which inserts into `table_c`.\n - Of course Query Events don't work with raw queries.\n\n___\nIf you find any typo then please edit and send a pull request.\n\n\u0026copy; 2016 [Juan Noriega](http://latinosoft.co/). Licensed under MIT license.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjsnoriegam%2Fpixie","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjsnoriegam%2Fpixie","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjsnoriegam%2Fpixie/lists"}