use whereHas and change "=<" to "<=" and no need of latest($date) just do latest()
How to fetch only fetch the latest relationship
I'm trying to optimise an eloquent query loading a lot of relationships with a lot of data.
The eloquent query fetches a list of documents with all it's relationships:
$query = Document::with(['relationship_a' => function ($q) use ($date) {
$q->where('date', '=<', $date)->latest('date');
}])
->with(['relationship_b' => function ($q) use ($date) {
$q->where('date', '=<', $date)->latest('date');
}])
...
->whereIn('document.id', [a lot of ids]);
I'm only interested in the newest record of every relationship.
My current query will fetch all the records of each relationship. It's imported this data isn't fetched to save memory / enhance performance. I tried with group by's, limits, max and so on. None of them worked as I expected.
with(['relationship_b' => function ($q) use ($date) { $q->limit(1) }])
Will one fetch one relationship for the first document (not all the documents
with(['relationship_b' => function ($q) use ($date) { $q->groupBy('date') }])
Won't allow me to order the relationship by date
with(['relationship_b' => function ($q) use ($date) { $q->where('date', max(...)); }])
Won't work because every relationship can have a different date
Please or to participate in this conversation.