Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Jatz's avatar
Level 6

Trouble defining relationships between three tables

This is probably a simple one but it is doing my head in. I am trying to define and access 3 tables with eloquent relationships but it proving difficult to wrap my head around. This is the Scenario.

There are three tables with the same model classes. Framework, FrameworkCategories and FrameworkOutcomes.

I want to find a framework and then display the categories and each outcome for the category like this.

Framework 1
    Category 1
        Outcome 1
        Outcome 2
        Outcome 3
    Category 2
        Outcome 1
        Outcome 2...

Relationships defined: A framework has many categories.

class Framework extends model{
     public function categories()
        {
            return $this->hasMany(FrameworkCategory::class);
        }

}

A category belongs to one framework. A category has many outcomes.

class FrameworkCategory extends model{

    public function outcomes()
        {
            return $this->hasMany(FrameworkOutcome::class);
        }

   
        public function frameworks()
        {
            return $this->belongsTo(Framework::class);
        }
}

An outcome belongs to one category.

class FrameworkOutcome extends model{
    public function category()
        {
            return $this->belongsTo(FrameworkCategory::class);
        }
}

This is what I am doing to call the relationships


$framework = Framework::find(1);

$categories = $framework->categories;

How do I call the outcomes for each category?

Is it possible to do it with eloquent or will this require some method which iterates through a collection and sorts them before displaying them?

BTW I can display a list of categories in my view but when I use tinker I get an error "logicException with message 'Relationship method must return an object of type...'

Tinker

$framework = App\Framework::find(1)
$framework
 App\Framework {#727
     id: 1,
     name: "Framework 1",
     created_at: "2016-12-04 09:54:28",
     updated_at: "2016-12-04 09:54:28",
   }

$framework->categories

The error above.

TIA

0 likes
0 replies

Please or to participate in this conversation.