I have 2 tables Contracts and Documents (one to many) and in documents I keep expiration_date for each document (which is nullable - not all documents has expiration_date).
I want to see for example all the contracts that will expire in april:
DB::table('contracts')
->leftJoin('documents', 'contracts.id', '=', 'documents.contract_id')
->whereNotNull('expiration_date')
->whereMonth('expiration_date', '04')
->whereYear('expiration_date', '2022')
->select('documents.contract_id', 'documents.is_contract', 'documents.expiration_date')
->get();
the problem is I am getting more entries then I need ... because there are documents for a contract that has more then one expiration_date filled.
How can I get the contracts that has set expiration_date but take only the latest value ?
ex:
Contract with id 128 has 3 documents:
document 1 => expiration_date: 01.04.2022
document 2 => expiration_date: null
document 3 => expiration_date: 21.04.2022
in this case get only one entry for contract id 128 with expiration_date => 21.04.2022
How can I do this ? I have tried to groupBy('contracts.id') but get an error:
Syntax error or access violation: 1055 Expression #23 of SELECT list is not in GroupBy clause and contains nonaggregated column...