I am facing a problem with an Eloquent relationship. I am new and trying to learn.
I have 3 models:
village
model - contain village names Patient
model - containing patient info Serial
model - containing patient serials village
model has many patients
and patient
belongs to the village
model
Patient
model has many Serial
models and the serial
model belongs to the patient
model
The serial
model has date fields. I am making queries to get Serials
whose dates match today
and try to get the related model data.
village
has many Patient
public function patient()
{
return $this->hasMany(Patient::class);
}
Patient
model belongs to village
public function village()
{
return $this->belongsTo(Village::class);
}
Patient
has many serials
public function serials()
{
return $this->hasMany(Serial::class);
}
Serial
belongs to patient
public function patient()
{
return $this->belongsTo(Patient::class);
}
I am getting Patient
using Serial::where('date', '2022-05-11')->with(['patient'])->get();
.
But I want to get the nested model like Serial::where('date', '2022-05-11')->with(['patient.village'])->get();
I am getting village
undefined! How can I get the village
through Serial
, please?
I find the error. I have problem with foreignId constrained I wrote relationship for patient like -
$table->integer('village')->nullable()
But it should be -
$table->foreignId('village_id')->constrained()->nullable()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.