php - Laravel 搜索参考第二个模型/集合/表与 orWhereHas?
问题描述
我正在尝试在我的刀片中为我的脚本模型实现搜索功能。对于与直接在脚本集合/表中搜索相关的所有内容,它都表现良好。但是,我的用户还需要能够输入 Patient first_name 或 last_name 并在 Script 表中搜索属于正在搜索的 Patient 的脚本记录。这些与 hasMany/belongsTo 关系有关。我正在尝试从脚本结果中的患者表中引用数据。
我已经尝试(在 SO 的帮助下)实现orWhereHas
和引用患者表,但我的语法必须关闭。
我尝试使用 orWhereHas 引用“患者”时收到的错误消息返回:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'scripts.patients_id' in 'where clause' (SQL: select count(*) as aggregate from `scripts` where exists (select * from `patients` where `scripts`.`patients_id` = `patients`.`id` and (`first_name` like %% or `last_name` like %%)))
如果它引用了,这可能会起作用patient_id
,这是患者外键的列名。不知道有没有办法做到这一点?
当我更改'patients'
为 时'patient'
,我收到错误:
Call to undefined method App\Script::patient()
楷模
Patient hasMany Script
Script belongsTo Patient (patient_id)
脚本刀片
{{ Form::text('search', $search, ['class' => 'form-control form-control-sm', 'placeholder' => 'Search Scripts...']) }}
{{Form::submit('Search', ['class' => 'btn btn-primary btn-sm'])}}
脚本控制器
$search = $request->search;
$patients = Patient::all();
$scripts = Script::
when($search, function ($query) use ($search) {
$query->where(function ($query) use ($search) {
$query
->where('prescribe_date', 'LIKE', '%' . $search . '%')
->orWhere('status', 'LIKE', '%' . $search . '%')
->orWhere('efax_reference', 'LIKE', '%' . $search . '%')
->orWhere('efax_confirmation', 'LIKE', '%' . $search . '%');
});
})
->orWhereHas('patients', function ($query) use ($search) {
$query->where('first_name', 'like', '%' . $search . '%')
->orWhere('last_name', 'like', '%' . $search . '%');
})
->paginate(25);
我希望如果有人在脚本表/模型的搜索输入中搜索患者姓名,他们能够交叉引用患者表/模型并显示这些患者的外键记录的脚本记录。
编辑:
患者模型
// One Patient has Many Scripts relationship
public function scripts() {
return $this->hasMany('App\Script');
}
脚本模型
// Many Scripts to One Patient relationship
public function patients() {
return $this->belongsTo('App\Patient');
}
解决方案
推荐阅读
- kotlin - 升级一些 Corda3 源代码以在 v4 上运行
- javascript - 是否有任何事件可以检测 win.reload 完成
- java - com.mysql.cj.jdbc.exceptions.CommunicationsException:从服务器成功接收的最后一个数据包是 XXXXXXXXXXXX 毫秒前
- android - 如何在片段中添加左垂直选项卡小部件
- python - 执行数学 sigma 和的最快、最有效和 python 的方法是什么?
- highcharts - 如何在 highchart 基本栏中添加自定义 y 轴?
- mysql - 如何识别缺少索引的慢查询?
- php - 事务在触发器中结束。批次已中止(在 PROCEDURE 上)
- css - 画布位于导航栏上方
- javascript - 哪个二维数组得到一维是最短的方法?