Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DerManoMann's avatar

Relationship from query?

Hi there,

I've got this model method that I would like to convert into a proper relationship. Is that possible? Basically I want to convert the query into a HasOne...

    public function bestOffer()
    {
        return $this->hasMany(Offer::class)->orderBy('amount, 'desc')->limit(1);
    }

0 likes
7 replies
aurawindsurfing's avatar

Hey @dermanomann

This does not really make sense. It obviously has many offers. You can delete all of the offers but one and just allow one, then turn your relationship into HasOne but is this really what you want?

public function offer()
    {
        return $this->hasOne(App\Offer);
    }
DerManoMann's avatar

In the end I stuck with what I had - it works and is simple. Only thing that is annoying is to call ->get()->first(); when accessing it; ie: ->bestOffer()->get()->first() which doesn't look very nice.

Please or to participate in this conversation.