yudijohn
yudijohn

Reputation: 1278

Laravel Where Condition on Grand Parent Eloquent Relation

I have 4 tables:

Account (id, name)

Type (id, account_id, name)

Category (id, type_id, name)

Money (id, category_id, date, amount)

And I defined the relations at model

But my problem is how to get money data with account id 2?

Account::find(2)-> type()-> category()->money

Is not working

Upvotes: 0

Views: 830

Answers (2)

lagbox
lagbox

Reputation: 50531

You can also go about this from the other direction if you only need the final result of 'money' and have the inverse relationships setup on the models.

$money = Money::whereHas('category.type.account', function ($q) use ($id) {
    $q->where('id', $id);
})->get();

// get() or first() depending whether these relationships return many

Laravel Docs - Eloquent Relationships - Querying Relationships - Querying Relationship Existence

Upvotes: 2

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111869

Assuming you created your relationships, you can do it this way:

$account = Account::with('type.category.money')->find(2);

and to display money you can now use:

echo $account->type->category->money->amount;

In above echo I of course assume for each record you have data in all those tables. If not, you'll need to add extra checking to make sure you don't display property for null

Upvotes: 2

Related Questions