staudenmeir/eloquent-json-relations

pivot always return the same data on belongsToJson

Closed this issue · 3 comments

Hi all, I facing a problem with the pivot data that always returns the same value, if the JSON contains multiple same user IDs

For example

Data in details column
image

# Model Class
protected $casts = [
   'details' => 'json',
];

public function approvers()
{
    return $this->belongsToJson(User::class, 'details->approvers[]->id');
}

Actual Pivot I got.

App\Models\User {#4790
  id: 1,
  name: "User 0001",
  pivot: Illuminate\Database\Eloquent\Relations\Pivot {#4791
    order: 3,
    status: true,
  },
},
App\Models\User {#4788
  id: 1,
  name: "User 0001",
  pivot: Illuminate\Database\Eloquent\Relations\Pivot {#4793
    order: 3, //expected => 2
    status: true,
  },
},
App\Models\User {#4789
  id: 1,
  name: "User 0001",
  pivot: Illuminate\Database\Eloquent\Relations\Pivot {#4795
    order: 3,  //expected => 1
    status: true,
  },
},

Expected

App\Models\User {#4790
  id: 1,
  name: "User 0001",
  pivot: Illuminate\Database\Eloquent\Relations\Pivot {#4791
    order: 3,
    status: true,
  },
},
App\Models\User {#4788
  id: 1,
  name: "User 0001",
  pivot: Illuminate\Database\Eloquent\Relations\Pivot {#4793
    order: 2, 
    status: true,
  },
},
App\Models\User {#4789
  id: 1,
  name: "User 0001",
  pivot: Illuminate\Database\Eloquent\Relations\Pivot {#4795
    order: 1, 
    status: true,
  },
},

Hi @yungts97,
I think it's not documented yet, but the package doesn't (and can't) support multiple pivot records with the same ID.

Do you need to use a JSON column? Laravel's native BelongsToMany relationships have better support for multiple pivot records with the same ID, but don't fully support every use case either.

Hi @staudenmeir,
May I know why it doesn't support with the same ID? But anyway, I decided to create a pivot table instead of storing them in JSON.

BelongsToJson would have be rewritten completely and would have to execute different and much more complex queries.