lmartins
1159
3
Eloquent

Group by 3rd level relationship

Posted 1 year ago by lmartins

Hi all,

Im building an app that has these 3 entities:

  • Assessment
  • Result
  • Category

They have these relationships:

class Assessment extends Model
{
    public function results()
    {
        return $this->hasMany(Result::class);
    }
}

class Result extends Model
{
    public function assessment()
    {
        return $this->belongsTo(Assessment::class);
    }
    public function question()
    {
        return $this->belongsTo(Question::class);
    }
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

class Category extends Model
{
    public function product()
    {
        return $this->belongsTo(Product::class);
    }
    public function questions()
    {
        return $this->hasMany(Question::class);
    }
}

My goal is to able from the Assessment view to list all Questions grouped by the Category, something like this:

View Purchase A

Category 1

  • Question 1.1
  • Question 1.2
  • Question 1.3

Category 2

  • Question 2.1
  • Question 2.2
  • Question 2.3

Is this something where I'll have to massage the data in the controller to achieve this format or does Eloquent have any way to approach this?

Please sign in or create an account to participate in this conversation.