'Problem with laravel eloquent relationship - can't access relationship
I am facing a problem with an Eloquent relationship. I am new and trying to learn.
I have 3 models:
villagemodel - contain village namesPatientmodel - containing patient infoSerialmodel - containing patient serials
Relationships
villagemodel has manypatientsandpatientbelongs to thevillagemodelPatientmodel has manySerialmodels and theserialmodel belongs to thepatientmodel
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.
Model codes
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?
Solution 1:[1]
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jamil90 |
