我有两张 table clinic
和service
。在 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/