Amanuel Nega Amanuel Nega - 6 months ago 35
PHP Question

Laravel Filter child row in hasOne relationship

I have this somewhere in my Laravel app

function result()
{
return $this->hasOne(InvestigationResult::class, 'assignment_id', 'id');
}


If the instance is rejected, another report is made and the result of the model should be the last instance of
InvestigationResult
but laravel takes the first instance.

How do I specify condition on a relationship. If it is possible, I would like to make complex quieries to filter rows eligible for the realtionship.

Answer

You can add any of the usual Eloquent database functions to a relationship.

For example, if you want to return a row only if rejected is false:

return $this->hasOne(InvestigationResult::class, 'assignment_id', 'id')
    ->whereRejected(false);