【问题标题】:How to join other table and count the row in laravel?如何加入其他表并计算laravel中的行数?
【发布时间】:2018-02-03 05:17:24
【问题描述】:

我正在计算每个求职者有多少需要职位。 我有两个表:jobseeker 和 jobposition。

求职者:

+----+---------+-----------+----------------+
| 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);

谁能帮助指导我?任何帮助将不胜感激。

【问题讨论】:

  • 您需要使用LEFT JOIN 来获得零计数。
  • @LawrenceCherone 兄弟,我的查询还不正确,甚至是拼写错误
  • 请参阅stackoverflow.com/questions/44928276/laravel-left-join-query 了解如何在 Laravel 中编写 LEFT JOIN
  • left join 需要与jobseeker 表和jobposition 表中的jobseeker id 相同,但就我而言,我在jobposition 表@Barmar 中没有jobseeker id
  • @Sohel0415,兄弟,我通过下面的答案得到了它。谢谢你回答我。

标签: php mysql laravel


【解决方案1】:

您想要的常规 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)

【讨论】:

  • 谢谢老哥,明白了,非常感谢
猜你喜欢
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 2018-11-09
  • 2012-11-03
  • 1970-01-01
  • 2015-07-10
  • 2018-02-27
  • 1970-01-01
相关资源
最近更新 更多