staudenmeir / eloquent-json-relations

Laravel Eloquent relationships with JSON keys

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

hasOneJson?

mattkingshott opened this issue · comments

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!

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! 🙏

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

Awesome!

Great stuff! Thank you 🙏🏻