mercredi 19 décembre 2018

Delete a field that contains a foreign key without delete all items that the field contains LARAVEL

in my DB I have users that contains foreign keys then when I want to delete a Store in my Laravel App, I can do it but for the property "delete('cascade)" all the items that the Store contains are deleted.

I want to delete whichever field, but without to delete all items that has relation with the user.

for example: In my app, I can create Users but each user has a store and that`s my foreign key, now... I can delete a Store in my app, but if I delete a store the User is deleted as well.

Schema::table('users', function(Blueprint $table){
        $table->engine = 'InnoDB';
        $table->unsignedInteger('store_id')->nullable()->after('direccion');
        $table->foreign('store_id')->references('id')->on('stores')->onDelete('cascade');
    });

In my Store model:

public function user()
{
    return $this->hasOne('App\User');
}

In my User Model

public function store()
{
    return $this->belongsTo('App\Store');
}

The same thing for other elements that I have, for example: I can create a ticket and the tickets contains foreign keys like: user_id and status_id. I think that would be the same problem that the Store element, right? I need help.

Ticket model:

public function user()
{
    return $this->belongsTo(User::class, 'usuario_id', 'id');
}

public function status()
{
    return $this->belongsTo('App\Status');
}

I want to keep the elements, in that case, if I want to delete a store, I don't want to delete the User that has that foreign key. And in case of tickets, I want to be able to delete a user, but keep the ticket save and vice versa.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire