#Updating pivot fields

4 messages · Page 1 of 1 (latest)

primal jay
#

I have a priority column in my pivot, as each item gets added to the intermediate table, the priority is always set to the max priority + 1, but when removing an intermediate row, i need to renumber the existing records. I am trying to do it like this, but they are not getting updated:

$service->voipRateGroups()->detach($rateGroup->id);
$service
  ->voipRateGroups()
  ->wherePivot('priority', '>', $priority)
  ->each(function ($vrg) use ($service){
    $newPriority = $vrg->pivot->priority -1;    
    $service
      ->voipRateGroups()
      ->updateExistingPivot($vrg->voip_rate_group_id, ['priority' => $newPriority]);
});
wide schooner
#

Something to consider is

  1. Does it actually matter if there are gaps in the priority?
    If not, then why touch all the other rows?
  2. Assuming it does matter, should updating the priorities trigger anything? If not then maybe you don't need to use each and can do it in a single DB query.
primal jay
#

they will only be added and removed via a service class, so they will not be updated, only added or removed

#

my issue with the above, is $vrg->voip_rate_group_id is always null... It should be $vrg->pivot->voip_rate_group_id