Chris J Allen
Chris J Allen

Reputation: 19207

Querying two levels of related data in Laravel

I have a Payment and a TransactionsGroup model. They are related via a BelongsToMany relationship.

The TransactionGroup is also related to Transactions via HasMany.

I want to get the Payments and related transactions. How would I do this using Eloquent? I've got this far:

    $payments = Payment::with('transactionGroups')->findOrFail($paymentId);

Thanks.

Upvotes: 0

Views: 55

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

You can load nested relations with the following code:

$payments = Payment::with('transactionGroups', 'transactionGroups.transactions')->findOrFail($paymentId);

Eloquent will load transactionGroups for given payment and then for each of them it will load related transactions. You can later access them the following way:

foreach ($payment->transactionGroups as $transactionGroup) {
  foreach ($transactionGroup->transactions as $transaction) {
    // your code here
  }
}

Upvotes: 1

Related Questions