如何从多个表中获取数据



我正在建立一个患者档案,其中有许多表格,如药物,治疗,x射线,患者信息等,所有这些都共享一个患者ID,但我觉得它会对服务产生很大的负担,需要时间,我搜索了很多,但我不知道这种方法是否好,或者它可以更好。下面是我的代码示例:

$patient = Patient::with(['country' => function ($q) {
$q->select('id', 'name');}])
->with(['city' => function ($q) {
$q->select('id', 'name');}])
->with(['recourse' => function ($q) {
$q->select('id', 'name');}])
->find($id);
$appointments = Appointment::where('patient_id', $id)                
->with(['branch' => function ($q) {
$q->select('id', 'name');}])
->with(['doctor' => function ($q) {
$q->select('id', 'first_name');}])
->with(['service_cat' => function ($q) {
$q->select('id', 'name');}])
->orderBy('id', 'ASC')
->get();
$invoices = Invoice::select('id', 'creditor_cat_id', 'final_price', 'status')->where('patient_id', $id)
->with(['service_cat' => function ($q) {
$q->select('id', 'name');}])
->get();

$medicine = Medicine::select('id', 'medicines_cats', 'start', 'end', 'status')->where('patient_id', $id)
->with(['medicinescats' => function ($q) {
$q->select('id', 'name');}])
->orderBy('status', 'ASC')
->get();
$medicine_cat = Medicine_cat::all();
$disease = Disease::select('id', 'disease_cats', 'start', 'end', 'status')->where('patient_id', $id)
->with(['diseasecats' => function ($q) {
$q->select('id', 'name');}])
->orderBy('status', 'ASC')
->get();
$disease_cat = Disease_cat::all();

$treatment = Treatment::select('id', 'treatment_cat_id', 'sessions', 'sessions_done', 'start', 'end', 'status')->where('patient_id', $id)
->with(['treatment_cat' => function ($q) {
$q->select('id', 'name');}])
->orderBy('status', 'ASC')
->get();
$treatment_cat = Treatment_cat::all();

$session_pat = Session_pat::select('id', 'services_cat_id', 'treatment_id', 'invoice_id', 'status')->where('patient_id', $id)
->with(['service_cat' => function ($q) {
$q->select('id', 'name');}])
->with(['treatment' => function ($q) {
$q->select('id', 'sessions');}])
->with(['invoice' => function ($q) {
$q->select('id', 'code', 'status');}])
->orderBy('status', 'ASC')
->get();
$service_cat_treat = Service_cat::where('type', 2)->get();

编辑:如果我使用hasMany,这些表有其他表连接如所示,所以我不知道如何使它,例如,患者表有治疗表,治疗表有2个表连接的发票和治疗类别,我做了上面从这些连接的表中获取所有数据

所以你有几个选项可以选择:

  • 将所有查询合并为单个查询(创建一个更大的查询,它将连接示例中所需的所有表)
  • 创建视图(在数据库中创建这些表的视图,然后使用该视图进行查询)
  • 创建物化视图(创建物化视图有它的好处,尽管维护它有点困难。由于物化视图实际上保存着真实的数据,这意味着它们需要与表同步。它们仅适用于需要快速获取数据且数据不会经常更改的情况。在你的情况下,它实际上可以工作,如果你同步物化视图每5分钟。)-警告:MySQL不直接支持物化视图。

如果你想提高速度,那么缓存你的结果,只检索在它之后插入的内容。

最新更新