【问题标题】:Delete all foreign key from one model Laravel 8从一个模型 Laravel 8 中删除所有外键
【发布时间】:2021-05-17 04:17:34
【问题描述】:
class Property extends Model
{
    use HasFactory;
    protected $guarded=[];

    public function Owner(){
        return $this->belongsTo(Owner::class);
    }
    public function Category(){
        return $this->belongsTo(Categpry::class);
    }
    public function Type(){
        return $this->belongsTo(Type::class);
    }
    public function Uses(){
        return $this->belongsTo(Uses::class);
    }
    public function Other(){
        return $this->hasOne(Other::class);
    }
    public function Street(){
        return $this->hasOne(Street::class);
    }
    public function Part(){
        return $this->hasOne(Part::class);
    }
    public function Pdf(){
        return $this->hasOne(Pdf::class);
    }
    public function Bill(){
        return $this->hasOne(Bill::class);
    }
    public function Numbers(){
        return $this->hasOne(Numbers::class);
    }
    public function Job(){
        return $this->hasOne(Job::class);
    }
}


public function up()
{
    Schema::create('proprietas', function (Blueprint $table) {
        $table->id();
        $table->string('nomeProprieta')->nullable();
        $table->string('int')->nullable();
        $table->string('floor')->nullable();
        $table->string('street')->nullable();
        $table->string('zip')->nullable();
        $table->string('city')->nullable();
        $table->foreignId('category_id')->constrained();
        $table->foreignId('type_id')->constrained();
        $table->foreignId('uses_id')->constrained();
        $table->timestamps();
    });
}

当我尝试通过控制器删除属性时,它给了我错误完整性约束违规:1451 无法删除或更新父行:外键约束失败。 我也尝试过使用 onDelete ('cascade')。 如果有人可以帮助我,我将不胜感激。

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    我想你的表引擎MyIsam,改成InnoDB

    $table->engine = 'InnoDB';
    

    并在您的迁移中添加onDelete('cascade')

    $table->foreignId('category_id')->constrained()->onDelete('cascade');
    $table->foreignId('type_id')->constrained()->onDelete('cascade');
    $table->foreignId('uses_id')->constrained()->onDelete('cascade');
    

    如果您想对所有表执行此操作,请将其从 /config/database.php 文件更改:

    'engine' => null,
    

    'engine' => 'InnoDB',
    

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 1970-01-01
      • 2021-10-25
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 2017-01-16
      相关资源
      最近更新 更多