maan56
4 months ago
1139
6
Laravel

nested relationship with groupBy and count

Posted 4 months ago by maan56

Hi, I'm having trouble getting a very-nested relationship to work correctly in laravel.

The wanted behavior is as follows,

I select an event by ID and I want to see which persons are subscribed to it and groupBy gender and count of gender grouping. Now the problem is there are some tables between the event and the person.

This is the query that works for getting nested relationship!

$events= Event::find($id)->with([
            'company'  => function ($query) {
                $query->select('id', 'name');
            }, 'company.persons'  => function ($query) {
                $query->select('id', 'name', 'gender');
            }
    ])->get();

Here are my models

Event Model

class Event extends Eloquent
{
    protected $table = 'events';

    public function company()
    {
        return $this->belongsTo('Company ');
    }
}

Company Model

class Company extends Eloquent {

    protected $table = 'companies';

    public function persons()
    {
        return $this->hasMany('Person');
    }

    public function events()
    {
        return $this->hasMany('Event');
    }
}

Person Model

class Person extends Eloquent
{
    protected $table = 'persons';

    public function company()
    {
        return $this->belongsTo('Company');
    }
}

I've tried many possibilities, I'm really stuck on this. Is it so difficult in laravel to achieve this kind of nested relationship linking?

Thanks

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