Problem when deleting relational data

Asked

Viewed 43 times

0

Gale need to delete data in cascade, by deleting the record from table users is not deleting data from table documents

Migration users:

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name', 70);
        $table->date('data_nascimento')->nullable();
        $table->string('sexo', 9)->nullable();
        $table->string('email')->unique();
        $table->string('nome_mae')->nullable();
        $table->string('foto_perfil', 180)->nullable();
        $table->string('tipo_pessoa', 40);
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
        $table->softDeletes();
    });
}

Migration document:

Schema::create('documentos', function (Blueprint $table) {
        $table->increments('id');
        $table->string('cpf', 15)->nullable();
        $table->string('rg', 30)->nullable();
        $table->date('data_expedicao_rg')->nullable();
        $table->string('orgao_emissor_rg', 50)->nullable();
        $table->string('cnpj', 20)->nullable();
        $table->string('ie', 30)->nullable();
        $table->string('sus', 50)->nullable();
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->on('id')->references('documentos')->onDelete('cascade');
        $table->timestamps();
        $table->softDeletes();
    });

Model User:

class User extends Authenticatable
{

    use Notifiable;
    use SoftDeletes;
    protected $table = 'users';

    public function documento()
    {
        return $this->hasMany('App\Models\Painel\Documento', 'user_id');
    }
}

Model document:

class Documento extends Model
{
    use SoftDeletes;
    protected $table = 'documentos';

    public function user()
    {
        return $this->belongsTo('App\User', 'user_id');
    }
}
  • Can you post the Models code? please.

  • I adjusted the post.

  • You are using SoftDelete() by chance you are not confusing? because the most existing data can be deleted in database??? what is your scenario?

1 answer

0


Try adding your User class the following method:

protected static function boot() {
    parent::boot();

    static::deleting(function($user) {
        $user->documento()->delete();
    });
}

There is also a lib of Cascade soft-Deletes, if interested you can take a look at this link:

https://github.com/michaeldyrynda/laravel-cascade-soft-deletes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.