It seems like you're trying to sort a collection of Dues based on a related Payment model's payment_date field. The error you're encountering is because the orderBy clause is being applied directly to the Dues query, which doesn't have a payment_date column.
To sort by a related model's column, you need to join the tables or use a subquery. Since you're using Spatie's Query Builder, you can use the join method to join the related payments table and then sort by the payment_date column.
Here's how you can modify your report method to include the default sort by payment_date:
public function report(Request $request): Response
{
$filter = $request->query("filter") ?? '';
$between = $filter === "" ? "" : explode(',', $filter['between']) ?? '';
return Inertia::render('Reports/TreasuryReport', [
'payments' => TreasuryReportResource::collection(QueryBuilder::for(Dues::class)
->allowedIncludes(['payments', 'user'])
->allowedFilters([
AllowedFilter::callback('between', function (Builder $query, $value) {
$query->whereHas('payments', function (Builder $query) use ($value) {
$query->whereBetween('payment_date', [$value[0], $value[1]]);
});
})
])
->join('payments', 'dues.id', '=', 'payments.dues_id') // Join the payments table
->defaultSort('payments.payment_date') // Default sort descending
->allowedSorts([
AllowedSort::field('paymentDate', 'payments.payment_date') // Sort by payment_date
])
->paginate(25)
->withQueryString()),
'filters' => $between
]);
}
Please note the following changes:
- I've added a
joinclause to join thepaymentstable with theduestable on thedues.idandpayments.dues_idcolumns. - I've changed the
defaultSortandallowedSortsto use the actual column namepayments.payment_dateinstead of the filter namepaymentDate. - The
AllowedSort::fieldmethod is used to specify the column name directly.
Make sure that the dues.id and payments.dues_id are the correct columns for joining the tables based on your database schema.
This should resolve the SQL error you're encountering and allow you to sort the Dues collection by the payment_date of the related Payment model.