Friday, March 17, 2017

Laravel Eloquent / Query Builder - select, sub-select and group concat

Can you help me with the problem below?

I have three models: - Email (table: 'emails', fields: 'id', 'email') - EmailRelGroup (table 'emails_rel_groups', fields: 'id', 'id_email', 'id_group') - Group (table: 'groups', fields 'id', 'group_name')

Emails can have more than one group and a group can have more than one email. Many-to-many relationship.

What is the best way for me to list the emails and their respective groups?

$sub_query = "
    (
        select group_concat(g.group_name separator ', ')
        from emails_rel_groups as r
        inner join groups as g
        where
            r.id_email = emails.id 
            and g.id = r.id_group
        limit 1
    ) as groups
";

$records = Email::select('id','email')
    ->selectRaw($sub_query_grupos)
    ->orderBy('email', 'asc')
    ->paginate(30);



via João Gabriel Casteluber Laass

Advertisement