如何在 laravel 5.6 中的 with() 块中使用 Eloquent 列名?

How to use Eloquent column name out of with() block in laravel 5.6?

我想在块中使用 eloquent 列名。
我试过 relationFunctionName.colun_nametableName.column_name 但它给了我一个错误。不存在这样的专栏。

我的查询:

$d = FormsValues::select('forms_values.id', 'forms_values.patient_id','forms_values.doctor_id')
                    // ->with('getUserPatientAssinged')
                    ->with(array('getUserPatientAssinged' => function($query) use($user) {
                        $query
                        ->select('form_value_id','consultation_assigned_by','date as consultation_date', 'start_time as consultation_start_time', 'end_time as consultation_end_time','doctor_id')
                    }));

--一些其他代码---

$d = $d->where('getUserPatientAssinged.doctor_id', Auth::user()->id);

有什么解决办法吗?
谢谢

通常,您不能在 ->with() 子句之外使用关系的列,除非您还使用了 ->join()。例如:

FormsValues::with(['getUserPatientAssinged' => function ($query) { ... }])
->where('assigned_patients.doctor_id', auth()->user()->id)
->get();

注意:假设一些 table 名称,因为您将引用它而不是关系名称

上面的代码可能会在 assigned_patients.doctor_id 作为未知列时引发错误,因为它在当前范围内不可用。这可以通过使用 ->join()->with() 子句来解决:

FormsValues::with(['getUserPatientAssinged' => function ($query) { ... }])
->join('assigned_patients', ...)
->where('assigned_patients.doctor_id', ...)
->get();

或者,我们可以使用 ->whereHas(),只要建立关系即可。为此,我们正在寻找 "assigned patient" 的 Doctor,因此:

FormsValues::with(['getUserPatientAssinged' => function ($query) { ... }])
->whereHas('getUserPatientAssigned.doctor', function ($query) {
  return $query->where('id', auth()->user()->id);
})->get();