Belongs To Through
Belongs To Through stats
- Downloads
- 3.2M
- Stars
- 934
- Open Issues
- 0
- Forks
- 77
Laravel Eloquent BelongsToThrough relationships
BelongsToThrough Laravel Package Summary
BelongsToThrough is a Laravel package designed to facilitate complex database relationships by providing an inverse version of the HasManyThrough relationship. This allows developers to define BelongsToThrough relationships with an unlimited number of intermediate models, enhancing the management of nested relationships in Laravel applications.
Key Features:
- Inverse Relationships: Enables defining inverse relationships for
HasManyThrough, allowing a model to belong to another through one or more intermediate models. - Support for Deep Relationships: Supports deep nested relationships through an array of intermediate models.
- Custom Foreign Keys: Allows specifying custom foreign keys for more tailored database queries.
- Table Aliases: Supports table aliases to resolve ambiguity when the relationship path includes the same model multiple times (Laravel 6+).
- Soft Deletes: Handles soft deleted records in relationships and allows including these records using
withTrashed().
Installation:
Install the package via Composer:
composer require staudenmeir/belongs-to-through:"^2.5"
For PowerShell users on Windows, use:
composer require staudenmeir/belongs-to-through:"^^^^2.5"
Usage:
After installation, use the BelongsToThrough trait in your model and define relationships as shown below:
Basic Usage:
class Post extends Model{ use \Znck\Eloquent\Traits\BelongsToThrough; public function country() { return $this->belongsToThrough(Country::class, User::class); }}
Deep Nested Relationships:
class Comment extends Model{ use \Znck\Eloquent\Traits\BelongsToThrough; public function country() { return $this->belongsToThrough(Country::class, [User::class, Post::class]); }}
Handling Soft Deletes:
class Comment extends Model{ use \Znck\Eloquent\Traits\BelongsToThrough; public function country() { return $this->belongsToThrough(Country::class, [User::class, Post::class]) ->withTrashed('users.deleted_at'); }}
Contributing:
Developers are encouraged to contribute to the package by following the guidelines linked in the repository's contributing section.
Credits:
Notable contributions have been made by Rahul Kadyan, Danny Weeks, and other community developers.
BelongsToThrough is a powerful tool for Laravel developers looking to streamline complex database relations in their applications, enhancing both flexibility and maintainability.
Lead Backend Developer: PHP, MySQL, Laravel, Statamic | @laravel Core Contributor