【问题标题】:Laravel, Detach() method to delete parent recordsLaravel, Detach() 方法删除父记录
【发布时间】:2018-12-19 20:16:14
【问题描述】:

大家好,我正在处理多对多关系,我想知道是否有任何方法可以删除主表的记录。

这是我的桌子

  Schema::create('inventario_inicial', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('producto_nombre_id')->unsigned();
        $table->foreign('producto_nombre_id')->references('id')->on('producto_nombre');
        $table->integer('existencias');
        $table->double('promedio');
        $table->timestamps();
    });
    Schema::create('empresa_inventario_inicial', function (Blueprint $table) {
        $table->integer('empresa_id')->unsigned();
        $table->foreign('empresa_id')->references('id')->on('empresas');
        $table->integer('inventario_inicial_id')->unsigned();
        $table->foreign('inventario_inicial_id')->references('id')->on('inventario_inicial');
    });

我可以使用此代码通过数据透视获取数据

$empresa = Empresa::find($request->empresa_id);
$empresa->inventario_inicial(); 

要分离 $empresa 的数据,我使用 $empresa->inventario_inicial()->detach();

它删除了数据透视表的记录是正确的,但我不仅要删除 empresa_inventario_inicial 中的内容,还要删除相关的 inventario_inicial 中的内容。类似于级联删除但从数据透视表中删除的东西。

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    您可以在迁移中使用$table->foreign('inventario_inicial_id')->references('id')->on('inventario_inicial')->onDelete('cascade')

    如果您不想级联,请考虑在删除inventario_official 时使用模型events 自动分离任何empresa_inventario_official 数据透视记录,然后使用$empresa->inventario_inicial()->delete() 方法代替上面的detach() .

    App\InventarioOfficial:

    protected $dispatchesEvents = ['deleting' => InventarioDeleting::class];
    

    然后你可以定义事件和事件的监听器:

    App\Events\InventarioDeleting

    class InventarioDeleting
    {
        use SerializesModels;
    
        public $inventario_official;
    
        public function __construct(InventarioOfficial $inventario_official)
        {
           $this->inventario_official = $inventario_official;
        }
    }
    

    App\Providers\EventServiceProvider

    public function boot()
    {
        parent::boot();
    
        Event::listen(\App\Events\InventarioDeleting::class, function ($io) {
            DB::('empresa_inventario_inicial')->where('inventario_inicial_id',$io->id)->delete();
            //or $io->empresas()->detach();
        });
    }
    

    【讨论】:

    • 嗨,谢谢你的回答,如果我删除inventario_inicial 中的特定记录,这将起作用,问题是如果我使用detach(),那么所有记录不仅会被删除在我的数据透视表中,但在主数据透视表中,如果我删除该表中的记录,级联将起作用。有没有办法做到这一点??
    • 我建议你换一种方式,即删除inventario_inicial,这会触发删除所有附加的empresa。这有什么不可行的原因吗?