Erich
Erich

Reputation: 2626

Laravel hasOne()->orderBy() vs hasOne()->ofMany()

One bit of "magic" in the Laravel codebase is here in HasOneOrMany.php where if the underlying query behind a hasOne relationship technically fetches multiple rows, it will just return the first row instead.

protected function getRelationValue(array $dictionary, $key, $type)
{
    $value = $dictionary[$key];
    return $type === 'one' ? reset($value) : $this->related->newCollection($value);
}

This got me thinking that, given a related model that is normally hasMany, an oldestOfMany() relation can be simulated with just an orderBy, e.g.

public function models() 
{
    return $this->hasMany(Model::class);
} 

public function firstModel() 
{
    return $this->hasOne(Model::class)->orderBy('created_at');
}

Are there any downsides to this shortcut approach?


As pointed out in the comments, calling ->first() on the many relationship works just fine for actually retrieving a model. In our app it's common to build relations from other relations, and I want to do that here. e.g.

public function firstActiveModel()
{
    return $this->firstModel()->active();
}

Upvotes: 1

Views: 470

Answers (0)

Related Questions