我正在用 laravel 编写一个应用程序,它显示此错误 SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'medicals' (SQL: select * from patients
left在 medicals
上加入 medicals
。patients_id
= patients
。id
left join 医疗
medicals
.trx_id
= patient_referral
.trx_id
)
return Patients::where(function ($q) use ($startdate, $enddate, $id) {
$q->where("patient_referral.trx_id", $id);
})
->leftJoin("medicals", "medicals.patients_id", "=", "patients.id")
->leftJoin("medicals", "medicals.trx_id", "=", "patient_referral.trx_id")
->get();
医学模型
class Medicals extends Model
{
protected $guarded = [];
public function patients()
{
return $this->belongsTo(Patients::class, "id", "patients_id");
}
public function tests()
{
return $this->belongsTo(Tests::class);
}
}
患者模型
类患者扩展模型 { protected $guarded = [];
public function medicals()
{
return $this->hasMany(Medicals::class);
}
public function patient_referral()
{
return $this->hasMany(PatientReferral::class);
}
患者转诊模型
类 PatientReferral 扩展模型 { protected $guarded = [];
protected $table = "patient_referral";
public function patients()
{
return $this->belongsTo(Patients::class);
}
}
最佳答案
您正尝试连接 medicals
表两次,因此在这种情况下,您需要为每个实例提供唯一的别名,并在连接子句中指定列的别名,以便数据库知道表中的确切列在过滤器中使用,例如
Patients::where(function ($q) use ($startdate, $enddate, $id) {
$q->where("patient_referral.trx_id", $id);
})
->leftJoin("medicals as a", "a.patients_id", "=", "patients.id")
->leftJoin("medicals as b", "b.trx_id", "=", "patient_referral.trx_id")
->get();
关于laravel - 语法错误或访问冲突 : 1066 Not unique table/alias: ',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65896762/