Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel group by, with relationship in different tables [duplicate]

Tags:

php

laravel

I am using laravel eloquent, trying to fetch information contained in different tables and compare them.

My tables are

tbl_checks
    id,check_id, person_id //person_id is the foreign key

tbl_persons
   id, category, 

I would like to fetch all people in table tbl_checks and group the data by person category tbl_persons.category.

In normal SQL statement it's like:

select from tbl_checks group by tbl_person.category where the tbl_persons.id is contained in tbl_checks.person_id

In my models I have:

class PersonsModel extends Model {
    //connect to the next database
    protected $connection = 'inspection';
    protected $table = 'tbl_trucks';

    //relation with tbl_checks

    public function checks(){
        return $this->hasMany('App\TblChecks','person_id','id');
    }
}

How can I use the ELoquent model, and not the Db facade? To make it abit clear. Am trying to find all persons who are in the table_checks and ignore persons id who are not in tbl_checks

like image 918
Geoff Avatar asked Apr 06 '18 16:04

Geoff


1 Answers

Assuming you have a person relationship in your TblChecks model:

TblChecks::with('person')->get()->groupBy('person.category');
like image 96
Jonas Staudenmeir Avatar answered Nov 09 '22 13:11

Jonas Staudenmeir