首页 > 解决方案 > 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');
}

标签: phplaravel

解决方案


推荐阅读