I am having an issue getting a hasManyThrough to work:
public function deliveryContainers() : HasManyThrough
{
return $this->hasManyThrough(
DeliveryContainer::class, // Final
StockMovement::class, // Intermediate
'product_id', // Foreign key on Intermediate
'id', // Foreign key on Final
'product_id', // Local key on Current
'location_id' // Local key on Intermediate
)->where('delivery_id', $this->delivery_id);
}
Because the stockMovements table returns multiple results, my resulting delivery containers collection contains duplicate entries. If I could somehow put a group/unique on the intermediate table query then this would be resolved.
I can get a collection with the correct deliveryContainers eager loaded using the following:
public function deliveryContainers()
{
return $this->hasMany(StockMovement::class, 'entity_id', 'delivery_id')
->with('deliveryContainer')
->where('product_id', $this->product_id)
->get()
->unique('location_id');
}
However, to access the deliveryContainer I now have the following:
foreach($this->deliveryContainers() as $row){
$row->deliveryContainer->id;
}
And what I would like to have...
foreach($this->deliveryContainers() as $row){
$row->id;
}
Is there any way to push the eager loaded relationship up a level (if that can be used to describe it), or even better add some kind of unique filter to the hasManyThrough relationship?
Table Structure
delivery_exceptions (where this relationship originates)
- product_id
- delivery_id
delivery_containers
- id
- delivery_id
stock_movements
- entity_id (linked to delivery id)
- product_id
Relationships
- A delivery exception belongsTo a product
- A product hasMany stock_movements
- A stock movement belongsTo a delivery container
- A delivery exception hasMany delivery containers... (indirectly, through a combination of the product and the stock movements)
delivery_containers
table? Because if so, why do you need ahasManyThrough
relationship at all? Ondelivery_exceptions
, you have adelivery_id
which you find again on thedelivery_containers
. So it looks quite straight forward to me... – Namoshek