class Container extends Model
{
public function boxes(): hasMany
{
return $this->hasMany(Box::class);
}
public function letters(): hasManyThrough
{
return $this->hasManyThrough(Letter::class, Box::class);
}
}
class Box extends Model
{
public function letter(): hasOne
{
return $this->hasOne(Letter::class);
}
}
class Letter extends Model
{
public function records(): hasMany
{
return $this->hasMany(Record::class);
}
}
@devondahon In your Container model, add this relationship:
public function records(): hasManyThrough
{
return $this->hasManyThrough(
Record::class, // The final model we want to reach
Box::class, // The intermediary model
'container_id', // Foreign key on the boxes table
'letter_id', // Foreign key on the records table
'id', // Local key on the containers table
'id' // Local key on the boxes table
);
}
@tisuchi Thanks very much for your answer.
However, it doesn't work in some cases. Maybe when some box or letter or record is missing, then the whole amount is null. Any idea to fix it ?
When a box or a letter or a record is missing, withSum('records', 'amount') will return null even if there are other valid values. I noticed the same behavior when using withCount('records').
I tried to fix it by using with such syntax: