The Laravel docs seem to indicate that the hasManyThrough
declaration can only be used for relationships that are two levels "deep". What about more complex relationships? For example, a User
has many Subject
s, each of which has many Deck
s, each of which has many Card
s. It's simple to get all Deck
s belonging to a User
using the hasManyThrough
declaration, but what about all Card
s belonging to a User
?
I created a HasManyThrough
relationship with unlimited levels: Repository on GitHub
After the installation, you can use it like this:
class User extends Model {
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function cards() {
return $this->hasManyDeep(Card::class, [Subject::class, Deck::class]);
}
}
As stated in the comments, hasManyThrough
doesn't support this level of specificity. One of the things you can do is return a query builder instance going the opposite direction:
//App\User;
public function cards()
{
Card::whereHas('decks', function($q){
return $q->whereHas('subjects', function($q){
return $q->where('user_id', $this->id);
});
});
}
We're going from Cards -> Decks -> Subjects
. The subjects
should have a user_id
column that we can then latch onto.
When called from the user model, it would be done thussly:
$user->cards()->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With