staudenmeir / eloquent-json-relations

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

belongsToJson dont works on array of objects #84

Open willGabrielPereira opened 1 year ago

willGabrielPereira commented 1 year ago

Hi all, i've been trying to make a relation with an array of objects, but it dont works

this is my relation $this->belongsToJson(Company::class, 'partner[]->id')

and this is my array 'partner' => [ [ 'id' => '100', 'status' => 'pending' ], [ 'id' => '5224', 'status' => 'pending' ],

here my stack trace if it helps https://flareapp.io/share/17DZQ4Xm#F68

staudenmeir commented 1 year ago

Hi @willGabrielPereira, What version of the package are you using? What's the result of dd($np->getAttributes()).

Please share the whole PartnerNetwork and Company model classes.

willGabrielPereira commented 1 year ago

Hi @staudenmeir, I'm using belongs-to-through v: 2.12.1 and eloquent-json-relations v: 1.6.3

All i can share from models is that, hope it's enough

class Company extends Model {
    protected $table = 'company';

    protected $fillable = [
        'id',
        'name',
        'domain',
        'domain_extra',
        'status',
        'document',
        'plan',
        'notes',
    ];
}
class PartnerNetwork extends Model {
    protected $table = 'partner_networks';

    protected $fillable = [
        'id',
        'company_id',
        'description',
        'manager',
        'partner',
        'active',
    ];

    public function partners()
    {
        return $this->belongsToJson(Company::class, 'partner[]->id')->withConfig('IMOVEL_REDE', true);
    }
}

Another info, if helps, is that the partner column is an array of objects like this [{"id": 5005, "status": "pending"}, {"id": 100, "status": "active"}]

staudenmeir commented 1 year ago

Did you add a JSON cast for partner?

willGabrielPereira commented 1 year ago

I'm using a custom cast that create an array of objects image

Using default cast json it works, but maybe can we change this to works with array of objects?

staudenmeir commented 1 year ago

I'm using a custom cast that create an array of objects

What does the code look like?

willGabrielPereira commented 1 year ago
use App\Helpers\Library\Cast;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class Objects implements CastsAttributes
{
    public function get($model, $key, $value, $attributes)
    {
        return self::cast($attributes[$key]);
    }

    public function set($model, $key, $value, $attributes)
    {
        return Cast::ArraySet($value);
    }

    public static function cast($value)
    {
        $object = json_decode((string) $value);

        if (!$object || (is_array($object) && !$object))
            return (object) [];

        return $object;
    }
}
staudenmeir commented 1 year ago

Should be possible but looks like a bit of a nightmare.