在这种情况下,我有患者模型和报告模型。患者Hasmany报告的地方。
<?php
namespace App;
use IlluminateFoundationAuthUser as Authenticatable;
use DB;
use SpatiePermissionTraitsHasRoles;
class Patient extends Authenticatable
{
public function reports()
{
return $this->hasMany('AppReports');
}
}
看来,我有所有针对他们的报告ID的患者的清单。我们有一个搜索患者模块,可以在其中搜索患者ID 和报告ID 的患者。我可以使用
来满足患者ID 的搜索$ data = detter :: where(" id"," like","%{$ search_patient}%")
,但无法根据报告ID 搜索患者和过滤结果的方案,因为使用Hasmany Wanterys
检索报告的数据以下是结果,患者数据来自患者模型,报告数据来自使用Hasmany关系的报告模型。我的要求是当我使用报告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"
}
]
}
]
这样的报告模型添加属于属于关系:
public function patient() {
return $this->belongsTo("AppModelsPatient", "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();
- 谁将执行搜索
- 使用急切的加载您指定的报告ID
首先在您的报告模型中添加一个属于属于:
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: []