Applying hasManyThrough to Deeper Relations

Laravel docs seem to indicate that an ad hasManyThroughcan only be used for relationships that are two levels of β€œdeep”. What about more complicated relationships? For example, a Userhas many Subjects, each of which has many Decks, each of which has many Cards. Just get everything Deckowned by a Userusing the ad hasManyThrough, but what about everyone Cardbelonging to a User?

+4
source share
2 answers

As stated in the comments, hasManyThroughthis level of specificity is not supported. One of the things you can do is to return an instance of the query builder in 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 are moving from Cards -> Decks -> Subjects. subjectsmust have a column user_idthat we can then snap into.

When invoked from a custom model, this will be done thussly:

$user->cards()->get();
+1
source

Well, in fact, the best solution would be to add an additional column to the Card table - user_id, if you often get all the cards for the user.

Laravel Has-Many-Through , . , Laravel , , .

, .

  • hasManyThough ,

, :

 public function decks()
    {
        return $this->hasManyThrough('Deck', 'Subject');
    }
  • hasMany

$deck_with_cards = $user->decks()->with("cards")->get();
$cards = [];
foreach($deck_with_cards AS $deck) {
  foreach ($deck->cards as $c) {
    $cards[] = $c->toArray();
  }
}

$cards $user.

0

Source: https://habr.com/ru/post/1664804/


All Articles