Laravel雄辩的构造

时间:2018-11-17 10:06:14

标签: laravel

我有这张桌子:

Attendances
id | member_id | attended_at
1  | 1         | 01/01/2018
2  | 2         | 01/01/2018
3  | 3         | 01/01/2018
4  | 4         | 01/01/2018
5  | 5         | 01/01/2018

Members
id | church_id
1  | 1
2  | 1
3  | 3
4  | 2
5  | 3

Churches
id | church_location
1  | Olongapo
2  | Bataan
3  | Subic

我的问题来自“出勤率”表,我需要知道每个教堂位置有多少人参加,以下是我需要的结果:

Olongapo - 2
Bataan - 1
Subic - 2

您能帮我填写下面的代码吗?

$attendances = Attendance::

1 个答案:

答案 0 :(得分:1)

给出该结果的原始SQL将如下所示:

select church_location, count(a.id) from churches as c
inner join members as m on c.id = m.church_id
inner join attendances as a on a.member_id = m.id
group by c.id;

现在要翻译一下,在Laravel中,我将从教会模型开始,而不是相反。

$attendances = Church::with(['members' => function($query) {
    $query->join('attendances as a', 'a.member_id', '=', 'members.id');
}])
->select([
  'church_location',
  DB::raw('count(a.id) as attendance')
]
->groupBy('id')->get();

您可能需要对其进行一些修改,就像我在没有现有模型的情况下将其转换为laravel一样,但是它应该与您想要的接近。原始查询在我尝试时肯定可以正常工作。

-编辑

要注意的另一件事是,您必须同时在模型中设置关系,才能使上面的代码正常工作。

-使用查询生成器进行编辑

DB::table('churches as c')
->select([
    'c.church_location',
    DB::raw('count(a.id) as attendance')
])
->join('members as m', 'm.church_id', '=', 'c.id')
->join('attendances as a', 'm.member_id', '=', 'm.id')
->groupBy('c.id')
->get();