0

I have a one to many relation between Person and Visit tables like this:

public function visits()
{
    return $this->hasMany('App\Models\Visit');
}

And want to get the persons who has a sickness_id of 1 in the relation like this:

$persons = Person::whereHas('visits', function ($query) {
    $query->where('sickness_id',  1);
})->get();

And it works fine but I want to search just last visit of each person.

I mean if a person has two visits, one with sickness_id of 1 and other with sickness_id of 2, do not return this person because last visit is sickness_id of 2.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Arman
  • 11
  • 6

3 Answers3

1

you can use hasOne relation for that:

public function lastVisit()
{
    return $this->hasOne('App\Models\Visit')->latest();
}

then you can load it:

$persons = Person::whereHas('lastVisit', function ($query) {
    $query->where('sickness_id',  1);
})->get();
OMR
  • 11,736
  • 5
  • 20
  • 35
0

I think the above answer is gonna work. Using addSelect, this might also work:

Person::addSelect('last_visit_id', Visit::select('id')
    ->whereColumn('person_id', 'persons.id')
    ->latest()
    ->limit(1)
)
->where('last_visit_id', 1)
->get();
Kevin Bui
  • 2,754
  • 1
  • 14
  • 15
-1
$person = modelname::query()
     ->where(['sickness_id' => '1' ])
     ->select('visits')
     ->orderBy('id', 'DESC')
     ->first();
Moshiur
  • 659
  • 6
  • 22
MIPro
  • 1
  • 2