PHPackages                             shortcodes/model-relationship - 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. shortcodes/model-relationship

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

shortcodes/model-relationship
=============================

This is package that eases to manage model relationships automatically handling them by observers

3.0.17(6y ago)13.3kmitPHP

Since Feb 7Pushed 6y agoCompare

[ Source](https://github.com/shortcodes/model-relationship)[ Packagist](https://packagist.org/packages/shortcodes/model-relationship)[ RSS](/packages/shortcodes-model-relationship/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (10)DependenciesVersions (37)Used By (0)

Package model-relationship
==========================

[](#package-model-relationship)

This is package that eases to manage model relationships automatically handling them by trait

Usage
=====

[](#usage)

All you need to do is to use **Relationship** trait to your model. Observer that is booted when You using a trait handle all relations:

> Remember to add `@relation` annotation above all your relation methods

How it works
============

[](#how-it-works)

When create or update action is triggered trait method automatically discovers relations in provided attributes and manage to handle them according to relation type.

### Handled relation types

[](#handled-relation-types)

- HasOne
- BelongsTo
- HasMany
- BelongsToMany

### Prequisites

[](#prequisites)

Lets assume we have an example Article model with relations

```
class Articel extends Model{

        /**
         * @relation
         */
        public function author()
        {
            return $this->belongsTo(Author::class);
        }

        /**
         * @relation
         */
        public function referrals()
        {
            return $this->hasMany(Referral::class);
        }

        /**
         * @relation
         */
        public function image()
        {
            return $this->hasOne(Image::class);
        }

        /**
         * @relation
         */
        public function tags()
        {
            return $this->belongsToMany(Tag::class);
        }

}

```

### HasOne

[](#hasone)

While adding `HasOne` relation there is few ways to do that

Providing image\_id

```
Article::create([...$someArticleAttributes,'image_id'=>$image_id]);

```

Providing image object with ID (all other attributes of image are being ignored)

```
Article::create([...$someArticleAttributes,'image'=> ['id'=>$image_id]]);

```

Providing image object without ID (image will be created and binded to article)

```
Article::create([...$someArticleAttributes,'image'=> ['url'=>'https://example.url','title'=>'Example title']]);

```

### BelongsTo

[](#belongsto)

While adding `BelongsTo` relation you can provide either `object_id` or object like notation `object['id']`

Providing author\_id

```
Article::create([...$someArticleAttributes,'author_id'=>$author_id]);

```

Providing author object with ID (all other attributes of author are being ignored)

```
Article::create([...$someArticleAttributes,'author'=> ['id'=>$author_id]]);

```

### HasMany

[](#hasmany)

While adding `HasMany` relation you should provide a collection of related objects

```
Article::create([...$someArticleAttributes,'referrals'=> [
    [
        'url'=>'https://example.url'
    ],
    [
        'url'=>'https://example.url'
    ],
    [
        'url'=>'https://example.url'
    ]
]);

```

While updating `HasMany` relation in `Article` you should provide a similar collection of related objects

```
$article->update(['referrals'=> [
    [
        'id'=>1,
        'url'=>'https://example.url'
    ],
    [
        'id'=>2,
        'url'=>'https://example.url'
    ],
    [
        'url'=>'https://example.url'
    ]
]);

```

If related model attributes contain `id` it will be updated. If it does not - it will be created and binded.

> IMPORTANT! In case above all referrals that are not in referrals attributes array will be deleted.

##### Adding new object to relation.

[](#adding-new-object-to-relation)

If you do not want to pass all present referrals ids to referrals array (so they would not be deleted) you can use postfix notation

```
$article->update(['referrals_add'=> [
    [
        'url'=>'https://example.url'
    ]
]);

```

Old referrals associated with article won't be affected.

> Note that if you provide already existing model (with id) to referrals\_add array it will be attached which is described below.

##### Removing new object to relation.

[](#removing-new-object-to-relation)

If you want to remove only one or few referrals without passing ids to referrals array (so they would not be deleted) you can use another postfix notation

```
$article->update(['referrals_delete'=> [
    [
        'id'=>1
    ]
]);

```

Old referrals associated with article won't be affected.

##### Attach already existing object to relation.

[](#attach-already-existing-object-to-relation)

If you want to associate existing models like referrals without assigned relation id (null) you can use postfix notation `_attach`

```
$article->update(['referrals_attach'=> [
    [
        'id'=>1
    ]
]);

```

Existing referrals will be associated with article.

##### Detach object from relation.

[](#detach-object-from-relation)

If you want to disassociate existing models like referrals (set foreign key to null) you can use postfix notation `_detach`

```
$article->update(['referrals_detach'=> [
    [
        'id'=>1
    ]
]);

```

Ids provided in referrals\_detach array will be disassociated from article.

> Remember that this feature require setting foreign key of relation to nullable in database

> Remember that association will be performed even if related object is associated with another model.

##### Ordering Relation objects

[](#ordering-relation-objects)

Sometimes you need to sort `hasMany` relations by `position`. In that case all you need to do is to simply pass referrals array with ids in order you want. This can be possible if related object (in this case referrals) have to contain `position` column in database.

```
$article->update(['referrals'=> [
    [
        'id'=>5
    ],
    [
        'id'=>3
    ],
    [
        'id'=>2
    ],
]);

```

> Remember that absent ids will be removed

### BelongsToMany

[](#belongstomany)

While adding `BelongsToMany` relation you should provide a collection of related objects ids

```
 Article::create([...$someArticleAttributes,'tags'=> [
        [
            'id'=>5
        ],
        [
            'id'=>3
        ],
        [
            'id'=>2
        ],
        [
            'id'=>1
        ],
    ]);

```

Above tags will be associated by `many-to-many` relation with Article.

If you want to pass additional data to pivot table simply add it to attributes table

```
 Article::create([...$someArticleAttributes,'tags'=> [
        [
            'id'=>5,
            'weight'=>1
        ],
        [
            'id'=>3,
            'weight'=>1
        ],
        [
            'id'=>2,
            'weight'=>3
        ],
        [
            'id'=>1,
            'weight'=>4
        ],
    ]);

```

> Since Laravel `belongsToMany` relation use `force` option to fill pivot table remember not to pass any fields that are not in database

##### Adding new object to relation.

[](#adding-new-object-to-relation-1)

You have also possibility to add one or few objects to belongsToMany relation using postfixes similar to `hasMany` relation with `_attach` postfix

```
$article->update(['tags_attach'=> [
    [
        'id'=>1
    ],
    [
        'id'=>2
    ]
]);

```

All tags absent in array associated with article won't be affected.

##### Removing new object to relation.

[](#removing-new-object-to-relation-1)

Same thing works for `_detach` prefix when you want ro remove association

```
$article->update(['tags_detach'=> [
    [
        'id'=>1
    ],
    [
        'id'=>2
    ]
]);

```

All tags absent in array associated with article won't be affected.

##### Ordering Relation objects

[](#ordering-relation-objects-1)

Simimilar to `hasMany` sometimes you need to sort `belongsToMany` associated relations by `position`. In that case all you need to do is to simply pass `tags` array with ids in order you want. This can be possible when there is `position` column in database on pivot table.

```
$article->update(['tags'=> [
    [
        'id'=>5
    ],
    [
        'id'=>3
    ],
    [
        'id'=>2
    ],
]);

```

> Remember that absent ids will be removed

Package is still under construction

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity72

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 ~13 days

Total

35

Last Release

2194d ago

Major Versions

1.1.0 → 2.0.02019-05-23

2.1.2 → 3.0.02019-08-21

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/30219536?v=4)[Roman Szymański](/maintainers/shortcodes)[@shortcodes](https://github.com/shortcodes)

---

Top Contributors

[![shortcodes](https://avatars.githubusercontent.com/u/30219536?v=4)](https://github.com/shortcodes "shortcodes (16 commits)")

### Embed Badge

![Health badge](/badges/shortcodes-model-relationship/health.svg)

```
[![Health](https://phpackages.com/badges/shortcodes-model-relationship/health.svg)](https://phpackages.com/packages/shortcodes-model-relationship)
```

###  Alternatives

[spatie/laravel-data

Create unified resources and data transfer objects

1.7k28.9M627](/packages/spatie-laravel-data)[touskar/php-socket-io-event-emitter

2612.4k](/packages/touskar-php-socket-io-event-emitter)[eureka2/g6k

Generator of simulator of calculation (calculator)

235.5k](/packages/eureka2-g6k)

PHPackages © 2026

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