PHPackages                             amethyst/relation-schema - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. amethyst/relation-schema

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

amethyst/relation-schema
========================

v0.3.3(2y ago)04325MITPHPPHP &gt;=8.2

Since Oct 19Pushed 2y ago1 watchersCompare

[ Source](https://github.com/amethyst-php/relation-schema)[ Packagist](https://packagist.org/packages/amethyst/relation-schema)[ RSS](/packages/amethyst-relation-schema/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (5)Versions (22)Used By (5)

Relation Schema
===============

[](#relation-schema)

[![Action Status](https://github.com/amethyst-php/relation-schema/workflows/Test/badge.svg)](https://github.com/amethyst-php/relation-schema/actions)[![Amethyst](https://camo.githubusercontent.com/938afa1bdd4820c0a11a02f7ec68d0519797fd7bde84651bf267db5203d3dca0/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7061636b6167652d416d6574687973742d376535376332)](https://github.com/amethyst-php/amethyst)

Create your own custom relations between Eloquent Models without altering the code.

Requirements
============

[](#requirements)

- PHP from 8.2 and later

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

[](#installation)

You can install it via [Composer](https://getcomposer.org/) by typing the following command:

```
composer require amethyst/relation-schema
```

The package will automatically register itself.

Initialization
--------------

[](#initialization)

Add `app('amethyst.relation-schema')->boot();` in any ServiceProvider in the method `boot`

Usage
-----

[](#usage)

A simple usage looks like this

```
use Symfony\Component\Yaml\Yaml;

app('amethyst')->get('relation-schema')->createOrFail([
    'name'    => 'parent',
    'type'    => 'BelongsTo',
    'data'    => 'foo',
    'payload' => Yaml::dump([
        'target' => 'bar',
    ]),
]);
```

Here's a list of all attributes with a brief explanation:

- name: The name of the relation. Can be only alphanumeric and it must start with a letter
- description: An optional field that will help to describe the relation
- type: The type of the relation. Values: `BelongsTo`, `HasMany`, `HasOne`, `MorphTo`, `MorphToMany`, `MorphToOne`, `MorphMany`
- data: The name of the data this relation start with. If a `Book` is related to an `Author` through the relation `BelongsTo` named `author`, then `book` is the data
- payload: A sets of information used to define better the relation, this changes based on the type of the relation. For example in a `BelongsTo` relation you'll neet a target, in the previous example `Author` is the target.

Whenever refering to any model, we will call it by name. For e.g. `\App\Models\Customer` will be `customer`. [More info](https://github.com/amethyst-php/core)

Keep in mind that this is an [Amethyst Package](https://github.com/amethyst-php/amethyst), if you wish to see the full list of available features and customization please check [core](https://github.com/amethyst-php/core)

Relationships
-------------

[](#relationships)

As said before, based on the `type` attribute, `payload` must have a different sets of value. It uses Yaml for the serialization, so for all examples we will use a `Symfony\Component\Yaml\Yaml` to convert from array to Yaml.

Most of relation uses the laravel-defined convention of names, such as `foreignKey` or `ownerKey`.

### BelongsTo

[](#belongsto)

Starting with the most simple relation, `BelongsTo`. It requires only the `target` parameter that indicate to which Model we are relating.

You can also set the `foreignKey` option.

So for example this new record

```
use Symfony\Component\Yaml\Yaml;

app('amethyst')->get('relation-schema')->createOrFail([
    'name'    => 'parent',
    'type'    => 'BelongsTo',
    'data'    => 'foo',
    'payload' => Yaml::dump([
        'target' => 'bar',
        'foreignKey' => 'foreign_key'
    ])
]);
```

is the exact same thing like this

```
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Foo
{
	public function parent(): BelongsTo
	{
		return $this->belongsTo(Bar::class, 'foreign_key');
	}
}
```

### HasMany and HasOne

[](#hasmany-and-hasone)

The inverse relationship of BelongsTo. They behave exactly the same.

Beside the `target` you can set `foreignKey` and `localKey`.

Now let's look an example of the same relationship in `BelongsTo` but inverted

```
use Symfony\Component\Yaml\Yaml;

app('amethyst')->get('relation-schema')->createOrFail([
    'name'    => 'children',
    'type'    => 'HasMany',
    'data'    => 'bar',
    'payload' => Yaml::dump([
        'target' => 'foo',
        'foreignKey' => 'foreign_key',
        'localKey' => 'local_key'
    ]),
]);
```

Will result in:

```
use Illuminate\Database\Eloquent\Relations\HasMany;

class Bar
{
	public function children(): HasMany
	{
		return $this->belongsTo(Foo::class, 'foreign_key', 'local_key');
	}
}
```

But wait, there's more! You can create relations with a custom subfilter. Say for example that having a `customer` and `invoice` you want to create a relation that retrieve all `invoices` with `status`:`paid` from your customer.

You can add another parameter called `filter` in the `payload`.

So having something like this: `filter: "status eq 'paid'"`. You can also use auto joins here, so for e.g. a query like: only the invoice that contains `Maintenance` in the name, will result in `filter: "status eq 'paid' and items.name ct 'Maintenance'"`.

Limitation: You cannot insert in the filter the same relation you're currently defining

### ManyToMany and BelongsToMany

[](#manytomany-and-belongstomany)

Not yet implemented.

### MorphTo

[](#morphto)

Similar to`BelongsTo` it doesn't require a `target`, instead it requires a `foreignKey` that in this case means the name of the field

### MorphToMany and MorphToOne

[](#morphtomany-and-morphtoone)

WIP

### MorphMany

[](#morphmany)

WIP

Api
---

[](#api)

There are no additional routes in this package, only the default provided by the [core](https://github.com/amethyst-php/core).

Testing
-------

[](#testing)

- Clone this repository
- Copy the default `phpunit.xml.dist` to `phpunit.xml`
- Change the environment variables as you see fit
- Launch `./vendor/bin/phpunit`

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~81 days

Recently: every ~319 days

Total

21

Last Release

770d ago

PHP version history (3 changes)v0.1.0PHP &gt;=7.1

v0.2.0PHP &gt;=7.2

v0.3.0PHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/ea4a9e56b247008aea4d20bb8a555a9f0cb69d0ac69aa8417b29fc37efa2eb5c?d=identicon)[railken](/maintainers/railken)

---

Top Contributors

[![railken](https://avatars.githubusercontent.com/u/26530231?v=4)](https://github.com/railken "railken (85 commits)")

---

Tags

laravelamethystrelation-schema

###  Code Quality

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/amethyst-relation-schema/health.svg)

```
[![Health](https://phpackages.com/badges/amethyst-relation-schema/health.svg)](https://phpackages.com/packages/amethyst-relation-schema)
```

PHPackages © 2026

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