Skip to content
Laravel Eloquent BelongsToThrough relationship
Branch: master
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src Support different database connections Feb 26, 2019
tests
.gitattributes
.gitignore Update .gitignore Feb 17, 2019
.scrutinizer.yml
.travis.yml
CODE_OF_CONDUCT.md
CONTRIBUTING.md
LICENSE Add license file Feb 1, 2019
README.md
composer.json Fix count and existence queries on Laravel 5.0–5.3 Feb 24, 2019
phpunit.xml.dist

README.md

Build Status Code Coverage Scrutinizer Code Quality Latest Stable Version Total Downloads License

Introduction

This inverse version of HasManyThrough allows BelongsToThrough relationships with unlimited intermediate models.
Supports Laravel 5.0+ and PHP 5.6+.

Installation

composer require staudenmeir/belongs-to-through

Usage

Consider this HasManyThrough relationship:
Country → has many → User → has many → Post

class Country extends Model
{
    public function posts()
    {
        return $this->hasManyThrough('App\Post', 'App\User');
    }
}

Use the BelongsToThrough trait in your model to define the inverse relationship:
Post → belongs to → User → belongs to → Country

class Post extends Model
{
    use \Znck\Eloquent\Traits\BelongsToThrough;

    public function country()
    {
        return $this->belongsToThrough('App\Country', 'App\User');
    }
}

You can also define deeper relationships:
Comment → belongs to → Post → belongs to → User → belongs to → Country

Supply an array of intermediate models as the second argument, from the related (Country) to the parent model (Comment):

class Comment extends Model
{
    use \Znck\Eloquent\Traits\BelongsToThrough;

    public function country()
    {
        return $this->belongsToThrough('App\Country', ['App\User', 'App\Post']);
    }
}

You can specify custom foreign keys as the fifth argument:

class Comment extends Model
{
    use \Znck\Eloquent\Traits\BelongsToThrough;

    public function country()
    {
        return $this->belongsToThrough(
            'App\Country',
            ['App\User', 'App\Post'], 
            null,
            '',
            ['App\User' => 'custom_user_id']
        );
    }
}

Contributing

Please see CONTRIBUTING and CODE OF CONDUCT for details.

Credits

You can’t perform that action at this time.