Antecedents
Recently, the company's back-end project has been transformed and upgraded, from the previous laravel5.6 version to laravel5.8 version. After the upgrade, the system generated a lot of SQL execution It was wrong, but it ran well in the old version of the system, so today's journey of digging holes was born.
Recommended: "laravel tutorial"
Project environment
Old system (linux laravel5.6 php7.2 mysql5. 7)
Upgraded new system (linux laravel5.8 php7.2 mysql5.7)
Only upgraded the laravel framework version, and did not upgrade other related service dependencies.
However, a large number of SQL execution errors occurred. The exception monitoring is as follows:
Analysis process
What caused this service error It is such a piece of business logic, which is simulated through a demo below.
$pivot = UserRole::firstOrCreate([ 'user_id' => 3, 'role_id' => 3, ]); $this->addRoleHistory($user,$pivot->id); dd($pivot->id);
In laravel5.6 version, this code runs without any problem, but upgrading to version 5.8 will cause a large number of SQL execution errors , like the following.
laravel5.6: dd($pivot->id); //10002 laravel5.8: dd($pivot->id); //null
In 5.6, the saved data can still get the ID normally, but why can’t it work in 5.8, so I immediately checked the release notes of laravel5.8, and there was nothing I found a change to cancel the acquisition of auto-increment ID in the Pivot model, so I started to check the 5.8 source code. . .
First of all, we compared the firstOrCreate function of 5.6 and 5.8 and found that there were no changes and the code logic was executed correctly.
Repair plan
In each Pivot Just re-overwrite the incrementing attribute value in Class and set it to true.class UserRole extends Pivot { public $incrementing = true; protected $fillable = [ 'user_id', 'role_id', ]; }
laravel5.8: dd($pivot->id); //10003
Postscript
So I looked at it carefully again In the laravel5.7~laravel5.8 release notes, I found that the reason for this change was still not mentioned, so I went to Google again and still couldn’t find the reason for this joke.The above is the detailed content of Disappeared Pivot model ID (Laravel pitfall diary). For more information, please follow other related articles on the PHP Chinese website!