如何在Laravel SQL查询中一起使用`GroupBy`和`join`

时间:2018-10-11 05:55:14

标签: mysql sql laravel

我有两个表clinicserviceservice表中有一列clinic_id。现在,我想检索每一列下的所有服务。

我正在提供一些演示数据以便更好地理解。

诊所表数据

{id:1,name:clinic1},{id:2,name: clinic2}

服务表数据

{id: 1, clinic_id: 1, name: service11}, 
{id: 2, clinic_id: 1, name: service12}, 
{id: 3, clinic_id: 2, name: service21}, 
{id: 4, clinic_id: 2, name: service22}

现在我要检索如下数据

{clinic_name: clinic1}:[{service_name: service11}, {service_name: service12}],
{clinic_name: clinic2}:[{service_name: service21}, {service_name: service22}]

Laravel的SQL查询是什么?

1 个答案:

答案 0 :(得分:1)

根据问题描述,雄辩的关系可以用来完成上述任务

根据Laravel的文档

  

“一对多”关系用于定义以下关系:   单个模型拥有任意数量的其他模型。例如,一篇博客文章   可能有无限数量的评论。像所有其他口才一样   关系,一对多关系是通过放置一个   在您的口才模型上发挥作用

请尝试使用以下代码段

  

app \ Models \ Clinic.php

#logo {position: absolute}
  

app \ Http \ Controllers \ ClinicController.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Clinic extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function services()
    {
        return $this->hasMany('\App\Models\Service','clinic_id','id');
    }
}
?>