6

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

Geoff
  • 6,277
  • 23
  • 87
  • 197
  • @Webinion The answer youve produced doesnt have an extra query to the related table, Am trying to get all persons contained in tbl_checks and ignore those that are not there and then get totals of those who are contained and group by person.category – Geoff Apr 06 '18 at 16:59

2 Answers2

21

Assuming you have a person relationship in your TblChecks model:

TblChecks::with('person')->get()->groupBy('person.category');
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
-1

If you are using Laravel >= 5.3, use Eloquent::has (Querying Relationship Existence):

$persons = PersonsModel::has('checks')->get();

For Laravel < 5.3, use Where Exists Clauses:

$persons = PersonsModel::whereExists(function ($q) {
    $q->select(DB::raw(1))->from('tbl_checks')
        ->whereRaw('tbl_persons.id=tbl_checks. person_id');
})->get();
Ben
  • 5,069
  • 4
  • 18
  • 26
  • Not sure your versions are correct; `has()` and `whereHas()` are both working fine on my `"laravel/framework": "5.0.*",` project. – Tim Lewis Apr 06 '18 at 20:38