F
Filament8mo ago
nowak

Summing TextColumn on nested relationship

I have a GroupOrderResource that has many UserOrder, with the relationship userOrders, then my UserOrder model has this relationship with ProductSku:
public function productSkus()
{
return $this->belongsToMany(ProductSku::class, 'product_sku_user_order')
->withPivot('quantity', 'price', 'product_name', 'product_variation', 'servings')
->withTrashed()
->withTimestamps()
->as('userOrderItem');
}
public function productSkus()
{
return $this->belongsToMany(ProductSku::class, 'product_sku_user_order')
->withPivot('quantity', 'price', 'product_name', 'product_variation', 'servings')
->withTrashed()
->withTimestamps()
->as('userOrderItem');
}
Then I want my TextColumn to show all ProductSku quantities for each Group Order, and my attempt was to do this:
TextColumn::make('userOrders.productSkus_sum_quantity')
->sum('userOrders.productSkus', 'quantity'),
TextColumn::make('userOrders.productSkus_sum_quantity')
->sum('userOrders.productSkus', 'quantity'),
But I get this error:
Call to undefined method App\Models\GroupOrder::userOrders.productSkus()
Call to undefined method App\Models\GroupOrder::userOrders.productSkus()
Is this an issue with attempting to sum a number from a nested relationship, or am I doing something else wrong?
Solution:
After some tinkering, I managed to do what I wanted like this: ```php TextColumn::make('userOrders.userOrderItems.quantity') ->label('Items') ->formatStateUsing(function ($state) {...
No description
Jump to solution
3 Replies
Povilas K
Povilas K8mo ago
I don't think Filament handles such nested relationship. Even on Eloquent level I'm not sure you would be able to run a similar query with "userOrders.productSkus". Maybe consider a hasManyThrough relation?
nowak
nowakOP8mo ago
Hmm can I create a hasManyThrough relationship on the GroupOrder model with the ProductSku model, through the UserOrder model? It is important for my operations that there is a ManyToMany relationship between UserOrder and ProductSku, so ProductSku does not have a user_order_id attribute that I can use for the hasManyThrough relationship directly.
Solution
nowak
nowak8mo ago
After some tinkering, I managed to do what I wanted like this:
TextColumn::make('userOrders.userOrderItems.quantity')
->label('Items')
->formatStateUsing(function ($state) {
$quantities = explode(', ', $state);
$totalQuantity = array_sum(array_map('intval', $quantities));
return $totalQuantity;
})
->summarize(Sum::make()),
TextColumn::make('userOrders.userOrderItems.quantity')
->label('Items')
->formatStateUsing(function ($state) {
$quantities = explode(', ', $state);
$totalQuantity = array_sum(array_map('intval', $quantities));
return $totalQuantity;
})
->summarize(Sum::make()),
No description
Want results from more Discord servers?
Add your server