staudenmeir / eloquent-json-relations

Laravel Eloquent relationships with JSON keys
MIT License
1k stars 63 forks source link

hasOneJson? #113

Closed mattkingshott closed 3 months ago

mattkingshott commented 3 months ago

Hi Jonas,

Amazing work as always!

Just wondered if it would be possible to do a hasOneJson instead of hasManyJson? Is there maybe a simple way to achieve this by chaining to hasManyJson?

Thanks!

mattkingshott commented 3 months ago

So based on my experimentation, it would appear that if you extend HasManyJson and replace ->get() within the getResults() method with ->first(), it works as expected.

e.g.

class HasOneJson extends HasManyJson
{
    /**
     * Retrieve the results of the relationship.
     *
     */
    public function getResults() : mixed
    {
        return ! is_null($this->getParentKey()) ? $this->first() : $this->related->newCollection();
    }
}

If this seems acceptable, it would be great if this could be merged in. Thanks! 🙏

staudenmeir commented 3 months ago

Hi @mattkingshott, I'll look into it. There also need to be some adjustments for eager loading, but it shouldn't be complicated.

mattkingshott commented 3 months ago

Awesome!

staudenmeir commented 3 months ago

I released a new version with the HasOneJson relation: https://github.com/staudenmeir/eloquent-json-relations?tab=readme-ov-file#hasonejson

mattkingshott commented 3 months ago

Great stuff! Thank you 🙏🏻