PHPackages                             tatter/relations - 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. tatter/relations

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

tatter/relations
================

Entity relationships for CodeIgniter 4

v2.1.1(3y ago)9022.3k↓11.5%21[6 issues](https://github.com/tattersoftware/codeigniter4-relations/issues)[3 PRs](https://github.com/tattersoftware/codeigniter4-relations/pulls)1MITPHPPHP ^7.4 || ^8.0CI passing

Since Sep 24Pushed 5mo ago7 watchersCompare

[ Source](https://github.com/tattersoftware/codeigniter4-relations)[ Packagist](https://packagist.org/packages/tatter/relations)[ Docs](https://github.com/tattersoftware/codeigniter4-relations)[ Fund](https://paypal.me/tatter)[ GitHub Sponsors](https://github.com/tattersoftware)[ RSS](/packages/tatter-relations/feed)WikiDiscussions develop Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (19)Used By (1)

Tatter\\Relations
=================

[](#tatterrelations)

Entity relationships for CodeIgniter 4

[![](https://github.com/tattersoftware/codeigniter4-relations/workflows/PHPUnit/badge.svg)](https://github.com/tattersoftware/codeigniter4-relations/actions/workflows/phpunit.yml)[![](https://github.com/tattersoftware/codeigniter4-relations/workflows/PHPStan/badge.svg)](https://github.com/tattersoftware/codeigniter4-relations/actions/workflows/phpstan.yml)[![](https://github.com/tattersoftware/codeigniter4-relations/workflows/Deptrac/badge.svg)](https://github.com/tattersoftware/codeigniter4-relations/actions/workflows/deptrac.yml)[![Coverage Status](https://camo.githubusercontent.com/8191ae2049fcff20e074982333449e80b9e76fa6779e367f5f129ce0ed230897/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f746174746572736f6674776172652f636f646569676e69746572342d72656c6174696f6e732f62616467652e7376673f6272616e63683d646576656c6f70)](https://coveralls.io/github/tattersoftware/codeigniter4-relations?branch=develop)

Quick Start
-----------

[](#quick-start)

1. Install with Composer: `> composer require tatter/relations`
2. Add the trait to your model: `use \Tatter\Relations\Traits\ModelTrait`
3. Load relations: `$users = $userModel->with('groups')->findAll();`
4. Add the trait to your entity: `use \Tatter\Relations\Traits\EntityTrait`
5. Load relations: `foreach ($user->groups as $group)`

(See also Examples at the bottom)

Installation
------------

[](#installation)

Install easily via Composer to take advantage of CodeIgniter 4's autoloading capabilities and always be up-to-date:

```
    > composer require tatter/relations
```

Or, install manually by downloading the source files and adding the directory to **app/Config/Autoload.php**\*.

Configuration (optional)
------------------------

[](#configuration-optional)

The library's default behavior can be altered by extending its config file. Copy **examples/Relations.php** to **app/Config/** and follow the instructions in the comments. If no config file is found in **app/Config** the library will use its own.

### Schemas

[](#schemas)

All the functionality of the library relies on the generated database schema. The schema comes from [Tatter\\Schemas](http://github.com/tattersoftware/codeigniter4-schemas) and can be adjusted based on your needs (see the **Schemas** config file). If you want to use the auto-generated schema your database will have follow conventional naming patterns for foreign keys and pivot/join tables; see [Tatter\\Schemas](http://github.com/tattersoftware/codeigniter4-schemas)for details.

Usage
-----

[](#usage)

Relation loading is handled by traits that are added to their respective elements.

### Eager/Model

[](#eagermodel)

**ModelTrait** adds relation loading to your models by extending the default model `find*`methods and injecting relations into the returned results. Because this happens at the model level, related items can be loaded ahead of time in batches ("eager loading").

Add the trait to your models:

```
	use \Tatter\Relations\Traits\ModelTrait
```

Related items can be requested by adding a `$with` property to your model:

```
	protected $with = 'groups';
	// or
	protected $with = ['groups', 'permissions'];
```

... or by requesting it on-the-fly using the model `with()` method:

```
$users = $userModel->with('groups')->findAll();
foreach ($users as $userEntity)
{
	echo "User {$user->name} has " . count($user->groups) . " groups.";
...
```

As you can see the related items are added directly to their corresponding object (or array) returned from the framework's model.

### Lazy/Entity

[](#lazyentity)

**EntityTrait** adds relation loading to individual items by extending adding magic `__get()`and `__call()` methods to check for matching database tables. Because this happens on each item, related items can be retrieved or updated on-the-fly ("lazy loading").

Add the trait and its necessary properties to your entities:

```
	use \Tatter\Relations\Traits\EntityTrait

	protected $table      = 'users';
	protected $primaryKey = 'id';
```

Related items are available as faux properties:

```
	$user = $userModel->find(1);

	foreach ($user->groups as $group)
	{
		echo $group->name;
	}
```

... and can also be updated directly from the entity:

```
	$user->addGroup(3);

	if ($user->hasGroups([1, 3]))
	{
		echo 'allowed!';
	}

	$user->setGroups([]);
```

Available magic method verbs are: `has`, `set`, `add`, and `remove`, and are only applicable for "manyToMany" relationships.

Returned items
--------------

[](#returned-items)

**Schemas** will attempt to associate your database tables back to their models, and if successful, **Relations** will use each table's model to find the related items. This keeps consistent the return types, events, and other aspects of your models. In addition to the return type, **Relations** will also adjust related items for singleton relationships:

```
// User hasMany Widgets
$user = $userModel->with('widgets')->find($userId);
echo "User {$user->name} has " . count($user->widgets) . " widgets.";

// ... but a Widget belongsTo one User
$widget = $widgetModel->with('users')->find($widgetId);
echo $widget->name . " belongs to " . $widget->user->name;
```

### Nesting

[](#nesting)

**ModelTrait** supports nested relation calls, but these can be resource intensive so may be disabled by changing `$allowNesting` in the config. With nesting enabled, any related items will also load their related items (but not infinitely):

```
/* Define your models */
class UserModel
{
	use \Tatter\Relations\Traits\ModelTrait;

	protected $table = 'users';
	protected $with  = 'widgets';
...

/* Then in your controller */
$groups = $groupModel->whereIn('id', $groupIds)->with('users')->findAll();

foreach ($groups as $group)
{
	echo "{$group->name}";

	foreach ($group->users as $user)
	{
		echo "{$user->name} is a {$user->role} with " . count($user->widgets) . " widgets.";
	}
}
```

### Soft Deletes

[](#soft-deletes)

If your target relations correspond to a CodeIgniter Model that uses [soft deletion](https://codeigniter.com/user_guide/models/model.html#usesoftdeletes)then you may include the table name in the `array $withDeletedRelations` property to include soft deleted items. This is particularly helpful for tight relationships, like when an item `belongsTo` another item that has been soft deleted. `$withDeletedRelations` works on both Entities and Models.

Performance
-----------

[](#performance)

*WARNING*: Be aware that **Relations** relies on a schema generated from the **Schemas**library. While this process is relatively quick, it will cause a noticeable delay if a page request initiates the load. The schema will attempt to cache to prevent this delay, but if your cache is not configured correctly you will likely experience noticeable performance degradation. The recommended approach is to have a cron job generate your schema regularly so it never expires and no user will trigger the un-cached load, e.g.:

```
php spark schemas
```

See [Tatter\\Schemas](http://github.com/tattersoftware/codeigniter4-schemas) for more details.

### Eager or Lazy Loading

[](#eager-or-lazy-loading)

You are responsible for your application's performance! These tools are here to help, but they still allow dumb things.

Eager loading (via **ModelTrait**) can create a huge performance increase by consolidating what would normally be multiple database calls into one. However, the related items will take up additional memory and can cause other bottlenecks or script failures if used indiscriminately.

Lazy loading (via **EntityTrait**) makes it very easy to work with related items only when they are needed, and the magic functions keep your code clear and concise. However, each entity issues its own database call and can really start to slow down performance if used over over.

A good rule of thumb is to use **ModelTrait** to preload relations that will be handled repeatedly (e.g. in loops) or that represent a very small or static dataset (e.g. a set of preference strings from 10 available). Use **EntityTrait** to handle individual items, such as viewing a single user page, or when it is unlikely you will use relations for most of the items.

###  Health Score

50

—

FairBetter than 96% of packages

Maintenance48

Moderate activity, may be stable

Popularity43

Moderate usage in the ecosystem

Community22

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 84% 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 ~79 days

Recently: every ~153 days

Total

14

Last Release

1404d ago

Major Versions

v1.0.3 → v2.0.02019-11-19

PHP version history (5 changes)v1.0.0PHP ^7.0

v2.0.0PHP ^7.1

v2.0.4PHP &gt;=7.2

v2.0.6PHP ^7.2|^8.0

v2.0.7PHP ^7.4 || ^8.0

### Community

Maintainers

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

---

Top Contributors

[![MGatner](https://avatars.githubusercontent.com/u/17572847?v=4)](https://github.com/MGatner "MGatner (63 commits)")[![eafarooqi](https://avatars.githubusercontent.com/u/3758194?v=4)](https://github.com/eafarooqi "eafarooqi (5 commits)")[![sfadschm](https://avatars.githubusercontent.com/u/40514119?v=4)](https://github.com/sfadschm "sfadschm (3 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![seunex17](https://avatars.githubusercontent.com/u/38796424?v=4)](https://github.com/seunex17 "seunex17 (2 commits)")

---

Tags

databasecodeigniterentitymappingrelationsRelationshipscodeigniter4

### Embed Badge

![Health badge](/badges/tatter-relations/health.svg)

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

###  Alternatives

[propel/propel1

Propel is an open-source Object-Relational Mapping (ORM) for PHP5.

8481.6M87](/packages/propel-propel1)[vlucas/spot2

Simple DataMapper built on top of Doctrine DBAL

605392.8k7](/packages/vlucas-spot2)[tatter/schemas

Database schema management, for CodeIgniter 4

2328.5k1](/packages/tatter-schemas)

PHPackages © 2026

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