php - Laravel / Eloquent : hasManyThrough WHERE -
in documentation of eloquent said can pass keys of desired relationship hasmanythrough.
lets have models named country, user, post. country model might have many posts through users model. said call:
$this->hasmanythrough('post', 'user', 'country_id', 'user_id');
this fine far! but how can these posts user id of 3 ?
can help here?
so here goes:
models: country
has many user
has many post
this allows utilize hasmanythrough
in question:
// country model public function posts() { homecoming $this->hasmanythrough('post', 'user', 'country_id', 'user_id'); }
you want posts of given user relation, so:
$country = country::first(); $country->load(['posts' => function ($q) { $q->where('user_id', '=', 3); }]); // or $country->load(['posts' => function ($q) { $q->has('user', function ($q) { $q->where('users.id', '=', 3); }); }) $country->posts; // collection of posts related user id 3
but easier, more readable , more eloquent if utilize instead: (since has nil country when looking posts of user id 3)
// user model public function posts() { homecoming $this->hasmany('post'); } // $user = user::find(3); // lazy load $user->load('posts'); // or utilize dynamic property $user->posts; // load posts automatically // or eager load $user = user::with('posts')->find(3); $user->posts; // collection of posts given user
to sum up: hasmanythrough
way nested relation directly, ie. posts given country, rather not search specific through
model.
php laravel relational-database eloquent
No comments:
Post a Comment