Skip to content

Relationships ​

Namespace: Unusualify\Modularous\Repositories\Logic\Relationships

Handles automatic synchronisation of all Eloquent relationship types when a record is saved. Composes CheckSnapshot and ResolveConnector to support special snapshot-sourced HasMany children and connector-resolved repositories.

Lifecycle Hooks ​

HookDescription
afterSaveRelationshipsMain sync handler — iterates all relationship types and syncs them from $fields
prepareFieldsBeforeSaveRelationshipsPre-processes HasMany fields: if the related model uses HasSnapshot, numeric IDs are wrapped into the expected snapshot source format
getFormFieldsRelationshipsLoads all relationship values back into $fields for form editing
afterForceDeleteRelationshipsDetaches all BelongsToMany relations when a record is hard-deleted

Relationship Type Handling in afterSaveRelationships ​

TypeSync MethodNotes
MorphToMany$object->{relation}()->sync($ids)Tags are excluded ('tags' is handled by TagsTrait)
MorphToSets _type / _id columns directly on the modelIterates configured types and matches from $fields
BelongsToMany$object->{relation}()->sync($payload)Payload may be a Collection, plain array, or pivot-keyed array
HasManyCreate / Update / Delete via the related RepositoryExisting IDs not in $fields are deleted via bulkDelete()
MorphManyCreate / Update / Delete directly on the related modelExisting IDs not in $fields are deleted via whereIn(...)->delete()

Whenever a sync produces changes (attached, updated, or detached > 0), TouchableEloquentModel::letEloquentModelBeTouched(true) is called to update the parent's timestamps.

Relation Discovery ​

The trait provides helpers used by MethodTransformers:

MethodReturnsDescription
getBelongsToManyRelationsarrayAll BelongsToMany methods on the model
getHasManyRelationsarrayAll HasMany methods on the model
getMorphManyRelationsarrayAll MorphMany methods on the model
getMorphToManyRelationsarrayAll MorphToMany methods on the model
getMorphToRelationsarrayParsed from morphTo input types in inputs() schema — returns ['morphToName' => [{name, model}, ...]]

Usage ​

php
// Relationships are synced automatically during Repository::update() / create().
// To define which relationships are managed, declare them on the model:

class Post extends Model
{
    public function tags(): MorphToMany { ... }
    public function categories(): BelongsToMany { ... }
    public function comments(): HasMany { ... }
}

// The form schema must include input names matching the relationship method names:
// ['type' => 'select', 'name' => 'categories', 'multiple' => true, ...]