3 years ago

whereHas latest child equals a value

Posted 3 years ago by patrykszady

Hi all,

Besides my problem, I'm really struggling with queries / Eloquent ... any pointes to good tutorials? (summing ->groupBy , etc).

I have a Project(hasMany) and Projectstatus(belongsTo) models. I'm trying to get all Projects where the latest('created_at') Projectstatus('status_id') for this/these Projects is 5:

This is what I have so far:

$projects = Project::whereHas('projectstatuses', function ($query) {
    $query->where('status_id', 5);

This returns all projects where status_id on the projectstatus table = 5, but a Project can have a few statuses throughout it's cycle. I only need this to get projects where the latest('created_at) title_id = 5.

Something like latest()->where('status_id', 5)->first() ? Where would I even put that?

After I figure this out, would this end up in the Model so I can call something like Project::active() to get all active projects?

Thanks so [email protected]! -Patryk

Please sign in or create an account to participate in this conversation.