Adds belongsToThrough relation to laravel models
First, pull in the package through Composer.
"require": {
"znck/belongs-to-through": "~2.0"
}
Within your eloquent model class add following line
class User extends Model {
use \Znck\Eloquent\Relations\BelongsToThroughTrait;
...
}
Consider a blog application. In this app, a country can have many users and a user can have many articles. So, hasManyThrough
provides easy way to access articles from a country.
class Country extends Model {
use \Znck\Eloquent\Relations\BelongsToThroughTrait;
public function articles () {
return $this->hasManyThrough(Article::class, User::class);
}
}
If we are accessing the country of the article, then we have to use $article->user->country
.
Class Article extends Model {
use \Znck\Eloquent\Relations\BelongsToThroughTrait;
public function country() {
return $this->belongsToThrough(Country::class, User::class);
}
}
Now, the magic: $article->country
Going deeper, City
-> District
-> State
-> Country
Class City extends Model {
use \Znck\Eloquent\Relations\BelongsToThroughTrait;
public function country() {
return $this->belongsToThrough(Country::class, [State::class, District::class]);
}
}