【问题标题】:SQLSTATE[23000]: Integrity constraint violation 1452 Cannot add or update a child row: a foreign key constraint failsSQLSTATE[23000]:完整性约束违规 1452 无法添加或更新子行:外键约束失败
【发布时间】:2021-09-29 20:39:40
【问题描述】:

我有这个迁移文件

class AddRolesFieldsToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->foreignId('role_id')->constrained();
            $table->string('student_address')->nullable();
            $table->string('student_licence_number')->nullable();
            $table->string('teacher_qualifications')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //

并且用户模型具有如下所示的所有可填充项

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'role_id',
        'student_address',
        'student_licence_number',
        'teacher_qualifications',
    ];

但是我得到了 SQLSTATE[23000]:完整性约束违规 1452 无法添加或更新子行:当我尝试注册新用户时外键约束失败,我应该如何解决这个问题?

【问题讨论】:

    标签: laravel-8 jetstream


    【解决方案1】:

    要解决此问题,请手动将角色值插入数据库。

    所以对于第一行:

    id=2 | name=Teacher | created_at =0000-00-00 00:00:00|updated_at 0000-00-00 00:00:00
    

    第二行:

    id=3 | name=Student| created_at =0000-00-00 00:00:00|updated_at 0000-00-00 00:00:00
    

    【讨论】:

      猜你喜欢
      • 2018-02-12
      • 2014-01-09
      • 2017-04-13
      • 2017-11-23
      相关资源
      最近更新 更多