0

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.