在这种情况下,我有患者模型和报告模型。患者有很多报告。
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use DB;
use Spatie\Permission\Traits\HasRoles;
class Patient extends Authenticatable
{
public function reports()
{
return $this->hasMany('App\Reports');
}
}
在一个视图中,我列出了所有患者的报告标签。我们有一个搜索患者模块,我们可以通过患者ID 和报告ID 搜索患者。我能够使用
满足患者ID 的搜索$ data = Patient :: where(&#34; id&#34;,&#34; LIKE&#34;,&#34;%{$ search_patient}%&#34;)
但由于正在使用hasMany关系检索报告数据,因此无法解决基于报告ID 搜索患者和过滤结果的方案
以下是结果,其中患者数据来自患者模型,而报告数据来自使用hasMany关系的Reports模型。我的要求是当我使用报告ID进行搜索时,我应该只能看到具有该报告ID和用户信息的数据。
[
{
"id": 1,
"group_id": 1000,
"date": "01-01-14",
"name": "Voss",
"address": "My Home 1",
"reports": [
{
"id": "ABC123",
"name": "Report1"
},
{
"id": "EDC123",
"name": "Report2"
}
]
},
{
"id": 2,
"group_id": 1000,
"date": "01-01-15",
"name": "Rosalia",
"address": "My Home 2",
"reports": [
{
"id": "RTC123",
"name": "Report3"
},
{
"id": "TYH123",
"name": "Report4"
}
]
}
]
答案 0 :(得分:2)
为您的报告模型添加belongsTo关系,如下所示:
public function patient() {
return $this->belongsTo("App\Models\Patient", "patient_id", "id");
}
然后在报告模型中执行搜索
$data = Report::with('patient')->where('id', $report_id)->get();
结果应如下所示
...
{
"id": ABC123,
"name": Report 1,
"patient": {
"id": 2,
"group_id": 1000,
"date": "01-01-15",
"name": "Rosalia",
"address": "My Home 2",
}
},
...
修改的: 如果您坚持以患者为基础,请执行以下操作:
Patient::whereHas('reports', function ($query) use($report_id) {
$query->where('id', $report_id);
})->with(['reports' => function ($query) use($report_id) {
$query->where('id', $report_id);
}])->get();
答案 1 :(得分:0)
首先在报表模型中添加belongsTo:
public function patient()
{
return $this->belongsTo(Patient::class);
}
然后像这样检索它:
$reportId = "ABC123"; //for demo purposses, you get this dynamically
$record = Report::where('record_id', '=', $reportId)->first();
// i used record_id, but you probably have just id;
$patient = $record->patient()->with('records')->first();
dd($patient);
结果是:
Patient {#199 ▼
#guarded: []
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:5 [▼
"id" => 1
"group_id" => 1000
"date": "01-01-15"
"name" => "Rosalia"
"created_at" => null
"updated_at" => null
]
#original: array:5 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"reports" => Collection {#204 ▼
#items: array:2 [▼
0 => Report {#207 ▶}
1 => Report {#209 ▶}
]
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []