I’m trying to make a custom table widget in filament for showing best selling products. When I do sum(quantity) as total_quantity
, it gives me Column not found
error. Here’s my entire code and the error message :
public function table(Table $table): Table
{
return $table
->query(
OrderDetails::query()
->selectRaw('product_id, sum(quantity) as total_quantity')
->groupBy('product_id')
->orderBy('total_quantity', 'desc')
)
->columns([
TablesColumnsTextColumn::make('product.name'),
TablesColumnsTextColumn::make('total_quantity'),
]);
}
Error message with the compiled SQL :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'total_quantity' in 'order clause'
select
count(*) as aggregate
from
`order_details`
group by
`product_id`
order by
total_quantity,
`order_details`.`id` asc
The weird thing is, as you can see, the compiled SQL code doesn’t have sum(quantity) as total_quantity
in it.
2
Answers
You can use the
orderByRaw
method and reference the column alias directly in the raw SQL for ordering.As I mentioned in a comment,
total_quatity
column isn’t available to sort the query, you’ll need to perform a subquery to achieve your desired result.You can try this instead: