Laravel group by,在不同表中有关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49697397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:36:40  来源:igfitidea点击:

Laravel group by, with relationship in different tables

phplaravel

提问by Geoff

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

我正在使用 laravel eloquent,试图获取包含在不同表中的信息并进行比较。

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_checksand group the data by person category tbl_persons.category.

我想获取表中的所有人tbl_checks并按人员类别对数据进行分组tbl_persons.category

In normal SQL statement it's like:

在普通的 SQL 语句中,它是这样的:

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

如何使用 ELoquent 模型,而不是 Db 外观?说得清楚一点。我正在尝试查找 table_checks 中的所有人员并忽略不在 tbl_checks 中的人员 ID

回答by Jonas Staudenmeir

Assuming you have a personrelationship in your TblChecksmodel:

假设您personTblChecks模型中有一个关系:

TblChecks::with('person')->get()->groupBy('person.category');

回答by Ben

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

如果您正在使用Laravel >= 5.3,请使用Eloquent::has查询关系存在):

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

For Laravel < 5.3, use Where Exists Clauses:

对于Laravel < 5.3,使用Where Exists 子句

$persons = PersonsModel::whereExists(function ($q) {
    $q->select(DB::raw(1))->from('tbl_checks')
        ->whereRaw('tbl_persons.id=tbl_checks. person_id');
})->get();