Search code examples
laravellaravel-5eloquenteloquent-relationship

How to Access nth Child from Within the Parent Eloquent Model


I have 4 tables with their corresponding models as follows:

//Table is applications
class Application extends BaseModel {
    public function bill(){
        return $this->belongsTo(Bill::class,'bill_id');
    }
}
//Table is bills
class Bill extends BaseModel {
    public function groups(){
        return $this->hasMany(Group::class,'group_id');
    }
}
//Table is groups
class Group extends BaseModel {
    public function items(){
        return $this->hasMany(Item::class,'item_id');
    }
}
//Table is items
class Item extends BaseModel {
    // some props
}

Every Application has Bill which is then divided into Groups. Each group has Items. Note that Items table is the one that defines item and the amount/unitprice of each item.

This is what I want:

From within the Application Model I want to define a function to return Items. I have tried the followings:

class Application extends BaseModel {

    ...

    public function billItems()
    {
        return $this->with('bill.groups.items');
    }

}

All I end up getting is:

"message": "\Application::billItems must return a relationship instance.",
"exception": "LogicException",

What's wrong. What can I do to get it working? I'm using Laravel 5.7


Solution

  • Perhaps idea like this will help?

    class Application extends BaseModel {
        ...
        public function billItems() {
            $items = [];
            $groups = $this->bill->groups()->get();
            foreach ($groups as $group) {
                $items[] = $group->items()->get();
            }
    
            return collect($items);
        }
    }
    

    If you like to get detail of bill, groups together with items, you might like to use merge result like Ramūnas Pabrėža suggested in the link.