So I have a Student model with this function:
public function latestStatus()
{
return $this->hasOne(StatusStudent::class)->latest();
}
then I just do a query with this latestStatus()
$query = Student::findOrFail(1);
$query = $query->whereHas('latestStatus', function($query) use ($statusuri) {
$query->where('status_id', 1);
});
dd($query->toSql());
and the toSql() function returns:
"select * from `students` where exists (select * from `status_student` where `students`.`id` = `status_student`.`student_id` and `status_id` = ?)
as if latest() is ignored.
Why doesn’t latest() add anything to the query?
Thanks.
Edit:
I tried adding selectRaw for example:
public function latestStatus()
{
return $this->hasOne(StatusStudent::class)->selectRaw('MAX(status_student.id)');
}
and still nothing appears in my query.
2
Answers
As stated in a comment by @matticustard,
Instead of
findOrFail(1)
usewhere('id', 1)
If you dig deeper to the
whereHas()
relationship. It calls thehas()
method then if you look for thehas()
method you will see thegetRelationWithoutConstraints()
method, means that it will call the relationship but it will remove all the constraints attach to it and will only call the base query instance :so if you use the
whereHas()
like the way you use it :it will return the query with out the
latest()
.Instead of doing it like that you can do it like :
Student Model
Controller
But since the relationship is define as
one-to-one
:or
Maybe you want to get the latest of all the status.