Eduardo Quiñonez
Eduardo Quiñonez

Reputation: 119

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.

Upvotes: 0

Views: 90

Answers (2)

Jesus Erwin Suarez
Jesus Erwin Suarez

Reputation: 1585

Try to have exchange the relationships

In your User.php

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

In your Store.php

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

Upvotes: 0

nakov
nakov

Reputation: 14268

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.

Upvotes: 4

Related Questions