Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying hasManyThrough to deeper relationships

Tags:

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 Subjects, each of which has many Decks, each of which has many Cards. It's simple to get all Decks belonging to a User using the hasManyThrough declaration, but what about all Cards belonging to a User?

like image 338
clb Avatar asked Dec 25 '16 01:12

clb


2 Answers

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]);
    }
}
like image 56
Jonas Staudenmeir Avatar answered Sep 23 '22 16:09

Jonas Staudenmeir


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();
like image 22
Ohgodwhy Avatar answered Sep 26 '22 16:09

Ohgodwhy