| Package Data | |
|---|---|
| Maintainer Username: | staudenmeir |
| Maintainer Contact: | hi@znck.me (Rahul Kadyan) |
| Package Create Date: | 2015-06-03 |
| Package Last Update: | 2025-02-20 |
| Home Page: | |
| Language: | PHP |
| License: | MIT |
| Last Refreshed: | 2025-10-30 15:02:33 |
| Package Statistics | |
|---|---|
| Total Downloads: | 7,781,384 |
| Monthly Downloads: | 259,298 |
| Daily Downloads: | 10,690 |
| Total Stars: | 1,256 |
| Total Watchers: | 19 |
| Total Forks: | 95 |
| Total Open Issues: | 0 |
This inverse version of HasManyThrough allows BelongsToThrough relationships with unlimited intermediate models.
Supports Laravel 5.0+ and PHP 5.6+.
composer require staudenmeir/belongs-to-through
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']
);
}
}
By default, soft-deleted intermediate models will be excluded from the result. Use withTrashed() to include them:
class Comment extends Model
{
use \Znck\Eloquent\Traits\BelongsToThrough;
public function country()
{
return $this->belongsToThrough('App\Country', ['App\User', 'App\Post'])
->withTrashed('users.deleted_at');
}
}
class User extends Model
{
use SoftDeletes;
}
Please see CONTRIBUTING and CODE OF CONDUCT for details.