staudenmeir / eloquent-json-relations

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

One dimensional array #93

Closed NomisGnos closed 1 year ago

NomisGnos commented 1 year ago

I have a JSON field for a model that saves the data into the database like this:

["1", "5", "10"]

The User model is setup for $table->json('units')->nullable();

However, how do I set that up with belongsToMany or belongsTo? Because the pointer in your readme seems to require it but laravel seems to be saving this as just a single dimentional array.

staudenmeir commented 1 year ago

Hi @NomisGnos, This is the README section that's relevant for you: https://github.com/staudenmeir/eloquent-json-relations#array-of-ids

staudenmeir commented 1 year ago

["1", "5", "10"]

Be aware that the types have to match, so these IDs need to be integers.

NomisGnos commented 1 year ago

I am using filament's repeater with this. It's storing the IDs as strings. Thus why they are not integers.

is there around that?

staudenmeir commented 1 year ago

return $this->belongsToJson(Unit::class, 'units');

This line is correct. How did you name the relationship? It shouldn't have the same name as the column (i.e. units), that causes all kinds of issues.

the biggest thing for me is the property from json. There is none in my case.

Do you mean the cast? array and json are the same.

This could be because the IDs are stored as "strings"...if that is the case, is there around that?

Some features of the relationship still work with strings but generally, there's no simple workaround. You need to find a way to take the strings from filemant and convert them to integers before storing them. You can try defining a custom accessor.

NomisGnos commented 1 year ago

I renamed the field to not be the same as the model name. Not sure if that fixed it or not but that seemed to work. Also, I don't have to typecast the array values. because it returned the correct values. Thank you for all the good work and help.