如何加入其他表并计算laravel中的行?

时间:2018-02-03 05:17:25

标签: php mysql laravel

我正在计算每个求职者需要多少位置。 我有两张桌子:求职者和工作岗位。

求职者:

+----+---------+-----------+----------------+
| id | fb_name | fullname  | desireposition |
+----+---------+-----------+----------------+
|  1 | John    | John Cena |              3 |
|  2 | Christ  | Christ    |              4 |
|  3 | Thomas  | Cfitcher  |              2 |
+----+---------+-----------+----------------+

职位:

+----+--------+------------------+
| id | job_id | require_position |
+----+--------+------------------+
|  1 |     12 |                3 |
|  2 |     13 |                3 |
|  3 |     14 |                4 |
|  4 |     15 |                5 |
|  5 |     16 |                4 |
|  6 |     17 |                3 |
+----+--------+------------------+

我的预期结果是:

+----+---------+-----------+----------------+-----------------------+
| id | fb_name | fullname  | desireposition | total_requireposition |
+----+---------+-----------+----------------+-----------------------+
|  1 | John    | John Cena |              3 |                     3 |
|  2 | Christ  | Christ    |              4 |                     2 |
|  3 | Thomas  | Cfitcher  |              2 |                     0 |
+----+---------+-----------+----------------+-----------------------+

我想计算每个求职者需要多少位置。

以下是我尝试使用crossJoin的内容,但我不确定我实际需要使用哪种联接。

$jobseekers = Jobseeker::crossJoin('jobpositions')
              >select('fullname','fb_name','desire_position', DB::raw('count(require_position) as total_requireposition'))
            ->groupBy('fullname')->paginate(10);

任何人都可以帮助指导我吗?任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:4)

您想要的常规MySQL查询是:

SELECT s.id, fullname, fb_name, desireposition, IFNULL(COUNT(require_position), 0) AS require_position
FROM jobseeker AS s
LEFT JOIN jobposition AS p ON s.desireposition = p.require_position
GROUP BY s.id

我不使用Laravel,但我认为翻译将是:

$Jobseeker->select('fullname','fb_name','desire_position', DB::raw('IFNULL(COUNT(require_position), 0) as total_requireposition'))
        ->leftjoin('jobposition', 'desireposition', '=', 'require_position')
        ->groupBy('jobseeker.id')
        ->paginate(10)