0

i need to search in last record of an relationship in Laravel 7. Here is my code, hope u understand my question :)

$Collection = ServiceRequest::whereHas('ServiceRequestSignatureFlows', function ($query) use ($ou_id) {
                                           return $query->latest()->where('user_id',666);
                                           })
                                           ->orderBy('name', 'ASC')
                                           ->get();

a ServiceRequest has many SignatureFlows, but i need only search on last flow inserted. I think that when i make ->latest(), my search could search 666 only in last rows, but doesnt happens. Thanks

2 Answers2

1

you can create the new relation HasOne and filter by it.

public function ServiceRequestSignatureLastFlow()
{
   return $this->hasOne(ServiceRequestSignatureFlows::class)->orderByDesc('id');
}

and than

$collection = ServiceRequest::whereHas('ServiceRequestSignatureLastFlow', function ($query) use ($ou_id) {
        $query->where('user_id', $ou_id);
    })->orderBy('name', 'ASC')->get();
V-K
  • 1,297
  • 10
  • 28
0

Remove the return inside the whereHas

McMazalf
  • 59
  • 1
  • 9