staudenmeir / eloquent-json-relations

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

Composite key for hasOne #118

Open AlexandreBonaventure opened 1 month ago

AlexandreBonaventure commented 1 month ago

Hello! I have been using your library to help with some json relationships and I found myself needing to build some relationships with composite keys. The problem I'm facing is that if I define the relationship like that:

class Media {
 public function book()
    {
             return $this->hasOneJson(Book::class, ['metadata->media_id', 'owner_id'], ['metadata->media_id', 'owner_id'])->where('type', 'Book');
    }
}

and eager-load it like that:

$owners->with('medias.book')

I get an error:

image

Because it seems like it is expecting the json key to be iterable. In the screenshot above, I tried a quick workaround that seems to work. Do you foresee problems with that ? Let me know if you want me to go ahead with a PR or not. Thanks!

staudenmeir commented 1 month ago

Hi @AlexandreBonaventure, Yeah, composite keys are only supported with many-to-many relationships at the moment. I'll look into it.

staudenmeir commented 1 month ago

Your workaround doesn't work with all types of composite keys, but you should definitely use for your app (if you aren't already):

I'll continue looking for a generic solution.