Skip to content

belongsToMany::sync The return primary key type is incorrect. #24141

@seth-shi

Description

@seth-shi
  • Laravel Version: 5.5.40
  • PHP Version: 7.1.13-nts

Description

There are many pairs of models. Syncing Associations.I've set my primary key to be a string, but belongsToMany::syncThe return is an integer, which overflows the integer and cannot get the correct result.This leads me to make an error on the primary key.

Steps To Reproduce:

hotelIds = $request->input('hotel_id', []);

$changes = $user->hotels()->sync($hotelIds);

event(new HotelUserEvent($user, $changes));

Screen

20180508101520.png

Steps To fix the issue:

# \Illuminate\Database\Eloquent\Relations\Concerns\InteractsWithPivotTable::class
protected function castKey($key)
{
        // whether the current key is greater than the largest integer.
        if ((int)bcsub($key, PHP_INT_MAX) > 0) {
            return (string)$key;
        }
        
        return is_numeric($key) ? (int)$key : (string)$key;
}

20180508104032.png
or directly depending on the primary key type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions