【问题标题】:Prevent row delete if column is referenced to another table PHP | Laravel | mysql如果列被另一个表引用,防止行删除 PHP |拉拉维尔 | mysql
【发布时间】:2020-04-02 14:49:08
【问题描述】:

我正在 Laravel 上创建一个库存管理系统(爱好项目)。但我有一些表,如 stock、device_type、locations 等。在“stocks”表上,有一个名为“device_type_id”的字段引用了“device_type”表上的“id”。我想以某种方式配置“device_type”表,如果“device_type”表的“id”与“stocks”表上的任何“device_type_id”匹配,则不能删除“device_type”表中的任何行。有什么建议吗?

'stocks' 表迁移

    public function up()
{
    Schema::create('stocks', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('device_type_id');
        $table->string('make');
        $table->string('model');
        $table->string('spec');
        $table->string('condition');
        $table->string('suk')->nullable();
        $table->date('purchase_date');
        $table->string('inv')->nullable();
        $table->string('location');
        $table->string('assigned_to');
        $table->timestamps();

        $table->foreign('device_type')
            ->references('id')
            ->on('device_type');
    });
}

'device_type' 表迁移

    public function up()
{
    Schema::create('device_type', function (Blueprint $table) {
        $table->id();
        $table->string('device_type');
        $table->timestamps();
    });
}

【问题讨论】:

    标签: php mysql database laravel


    【解决方案1】:

    首先创建 device_type 表迁移,然后创建 stock 表迁移。

    并在stocks表迁移中写入外键如下:

    $table->foreign('device_type_id')->references('id')->on('device_type');
    

    【讨论】:

      【解决方案2】:

      您可以添加一个用于删除类型的列表器并检查该类型是否被引用,然后不要删除它,否则您可以删除它:

      DeviceType模型中添加这个方法:

      protected static function boot()
      {
          parent::boot();
      
          static::deleting(function($type) {
              // assuming you have stocks relationship in your DeviceType model
              if ($type->stocks()->count() > 0) {
                  return false;
              }
          });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-12
        • 1970-01-01
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        • 2019-06-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多