简体   繁体   中英

Query builder filter based on related records sum

I would appreciate some help regarding laravel/octobercms query builder. I have two models/tables as follows:

CV model has many Experiences, Experience model belongs to CV.

CVs table  
| id | user_id |  
| --- | ------ |  
| 1 | 11 |  
| 2 | 22 |  



Experiences table  
| id | cv_id | from | to |  
| --- | ------ | ----- | --- |  
| 1 | 1 | 2019-01-01 | 2020-01-01 |  
| 2 | 1 | 2020-05-02 | 2021-09-01 |   
| 3 | 2 | 2019-01-01 | 2019-05-01 |  
| 4 | 2 | 2020-01-01 | 2021-05-01 |   

I'm trying to use query builder to filter CV's based on Experiences duration. For example, CV with id: 2, has two experiences with id 3 and 4, each with 4 moths of experience, so in total CV with id: 2 has 8 months of experience.

So far I tried variations of:

$query = Cv::query()->whereHas('experiences', function ($query) {
        $query->addSelect(DB::raw("SUM(DATEDIFF(COALESCE(`to`, CURDATE()), `from`)) AS sum_experience"));
    });

Above produces:

select * from `cvs` where exists (select *, SUM(DATEDIFF(COALESCE(`to`, CURDATE()), `from`)) AS sum_experience from `cv_expriences` where `cvs`.`id` = `cv_expriences`.`cv_id`)

But I don't know how can I compare sum_experience value, to a value I need. Any help is appreciated.

It would be great if you can just calculate experience in a month while adding/updating records of the Experiences table and add it directly to the CV table .

It will make things really easy for you to manage and search from it as well as less complex DB queries will increase response time

if any doubt please comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM