Knowing the structure below, can I add a function to the Container
class to get records
directly with Container::with('records')->get()
instead of Container::with('boxes.letter.records')->get()
?
containers
hasMany
boxeshasOne
letterhasMany
records
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);
}
}
2
Answers
Yes, you can indeed create a hasManyThrough relationship from Container to Record by chaining the relationships like this:
But make sure you should have proper foreign keys defined in database tables.
Solution # 1 (
hasManyThrough
with joins)Yes, you can access the records of a 3rd table directly through the use of
hasManyThrough
, however need usejoins
to will can connect more tables.Solution # 2 (
hasManyDeep
by package)Package: staudenmeir/eloquent-has-many-deep
However, this allows you to quickly handle this multi-table relationship. With
hasManyDeep
, you can define complex relationships across multiple tables with ease.About hasManyDeep from Laravel News