关于LaraCSV,我的收藏/模型关系遇到了一些问题。这是其文档:https://github.com/usmanhalalit/laracsv#full-documentation。我现在有3个可以互动的模型:医生,患者,脚本
Doctor belongsToMany Patient
Patient belongsToMany Doctor
Patient hasMany Script
Script belongsTo Patient
我还在Doctor模型中创建了一个关系链接,该链接可用于将Doctor与脚本相关联,但在这种情况下似乎不起作用:
public function scripts() {
$this->load(['patients.scripts' => function($query) use (&$relation) {
$relation = $query;
}]);
return $relation;
}
我正在尝试做的是允许管理员和我们的用户下载包含所有脚本的CSV文件。虽然这对于管理员人员来说很好用,因为我可以直接引用模型,但由于它们与医生联系在一起,因此我无法使其对用户有用,而且我似乎无法像平常一样将其与脚本联系起来。这是适合管理员的完美工作版本:
$doctors = Doctor::orderBy('last_name', 'asc')->get();
$patients = Patient::orderBy('last_name', 'asc')->get();
$scripts = Script::orderBy('prescribe_date', 'desc')->get();
$csvExporter->beforeEach(function ($script) use ($doctors, $patients) {
$patient = $patients->where('id', $script->patient_id)->first();
$doctor = $patient->doctors->first();
$script->patient = $patient->full_name;
$script->doctor = $doctor->full_name;
});
以下是用户特定版本的显示方式:
$doctors = User::
find(Auth::user()->id)
->doctors()
->orderBy('last_name', 'asc')
->get();
$patients = Patient::orderBy('last_name', 'asc')->get();
$scripts = $doctors->scripts()->get();
尝试链接我的Doctor模型scripts()
函数会导致错误:Method Illuminate\Database\Eloquent\Collection::scripts does not exist.
$doctors = User::
find(Auth::user()->id)
->doctors()
->orderBy('last_name', 'asc')
->get();
$patients = array();
$scripts = array();
foreach ($doctors as $doctor_fe) {
foreach ($doctor_fe->patients as $patient_fe) {
$patients[] = $patient_fe;
foreach ($patient_fe->scripts as $script_fe) {
$scripts[] = $script_fe;
}
}
}
我也尝试使用数组提取信息,但不幸的是,它必须是通过以下错误传递的集合:Argument 1 passed to Laracsv\Export::addCsvRows() must be an instance of Illuminate\Database\Eloquent\Collection, array given
答案 0 :(得分:0)
我通过将所有属于用户医生的患者放置在一个foreach循环中来解决,然后使用另一个患者来获取患者的ID。然后,我获取患者的id数组,并使用whereIn函数比较脚本的Patient_id字段以获取正确的条带。
$doctors = User::
find(Auth::user()->id)
->doctors()
->orderBy('last_name', 'asc')
->get();
$patients_array = array();
foreach ($doctors as $doctor_fe) {
$patients_fe = $doctor_fe->patients;
foreach ($patients_fe as $patient_fe) {
$patients_array[] = $patient_fe->id;
}
}
$patients = Patient::orderBy('last_name', 'asc')->get();
$scripts = Script::whereIn('patient_id', $patients_array)->get();
$csvExporter->beforeEach(function ($script) use ($doctors, $patients) {
$patient = $patients->where('id', $script->patient_id)->first();
$patient_initials = substr($patient->first_name, 0, 1) . substr($patient->last_name, 0, 1);
$doctor = $patient->doctors->first();
$script->patient = $patient_initials;
$script->doctor = $doctor->full_name;
});
答案 1 :(得分:0)
如果我正确地解释了您的问题,则您希望获取医生所有患者的所有脚本。 Laravel为此提供了hasManyThrough()
方法:
class Doctor extends Model
{
/**
* Get all of the scripts for the patient.
*/
public function scripts()
{
return $this->hasManyThrough(App\Script::class, App\Patient::class);
}
}
第一个参数是您要获取的模型(脚本);第二个参数是中间模型(患者)。
要使用它:
$doctor = Doctor::first();
$scripts = $doctor->scripts;