Search code examples
laravellaravel-5foreign-keyssql-delete

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.


Solution

  • In my opinion the mistake is in the way you've setup the relationship.

    So if the user has one store, then you should add a user_id in your stores table, and not the other way around.

    Then your models should be like this:

    Store.php

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

    and your User.php

    public function store()
    {
        return $this->hasOne(Store::class);
    }
    

    This with your cascading option will mean that whenever the User is deleted from the system you would want its store to be removed. When the Store will be removed the user will have no store, but the user will still exist.