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

标签 mysql sql laravel

我有两张 table clinicservice。在 service 表中有一列 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 查询是什么?

最佳答案

根据问题中提到的描述, Eloquent 关系可以用来完成上述任务

根据 Laravel 文档

A "one-to-many" relationship is used to define relationships where a single model owns any amount of other models. For example, a blog post may have an infinite number of comments. Like all other Eloquent relationships, one-to-many relationships are defined by placing a function on your Eloquent model

请尝试以下代码片段

app\Models\Clinic.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');
    }
}
?>

app\Http\Controllers\ClinicController.php

<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Clinic;
use App\Http\Controllers\Controller;
use App\Http\Requests;

class ClinicController extends Controller
{
/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{

}

 function index()
 {
   $Clinics = Clinic::with('services')->get();
 }
}
?>

关于mysql - 如何在 Laravel SQL 查询中一起使用 `GroupBy` 和 `join`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52753142/

相关文章:

mysql - 根据mysql中的特定列切换行和列

mysql - 动态表有点像 View ,但有一个可更新的额外列?

ASP.NET 在存储过程中执行计算,或在 Gridview 中的数据绑定(bind)中执行计算

php - Laravel 4 - 从包中扩展应用程序 Controller

python - 有没有办法从 IOS 应用程序调用 flask 应用程序中的多个获取和发布请求

c# - 执行 IEnumerable 查询时如何获取特定数量的记录?

sql - 选择使用来自 oracle 的 2 个字段删除重复条目

php - 如何在 digitalocean 应用程序上正确部署 laravel nova

laravel - 在 Laravel 项目中使用 Vuepress

php - 添加增加的时间到日期(php)