How to cascade on softdeletes in Laravel4? - laravel

Tried to use foreign keys with delete cascade and softDeletes without much luck.
I have 2 tables: Users, Events. Both tables have softDeletes.
Users can have 0..n Events.
Events have an user_id, used as foreign key on users, like this:
$table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE')->onUpdate('CASCADE');
Problem is, when I delete an User, it gets soft-deleted, but its Events do not - either soft deletion or physical deletion.
Am I doing something wrong, or is this the correct Eloquent behavior?
Secondly, if that is the correct behavior, how to best implement deletion cascade? maybe overriding the delete() method in my Models like this ...
public function delete()
{
//delete all events...
__parent::delete()
}
?

The DB's foreign key won't do anything because you haven't changed the primary key in question. Only if you update or delete the primary key will the related rows be modified.
From everything I can find about this topic, the solution is to use Eloquent's Model Events to listen for a delete event, and update the related tables.
Here's one StackOverflow question about it.
Alternatively, you can "extend" the delete() method and include the functionality directly as well. Here's an example.

You're overthinking this.
Either just delete the events right before you delete the users:
$user->events()->delete();
$user->delete();
Or create a customer delete function in the user model:
public function customDelete(){
$this->events()->delete();
return $this->delete();
}
You could also add a model observer and watch for the deleting or delete event, but in the scenario you mentioned above, the previous two methods would be a more simple solution.
http://laravel.com/docs/4.2/eloquent#model-observers

If I understand correctly, you are trying to cascade softdeletes in both tables?
I believe to do this with ON UPDATE CASCADE is not the correct approach. I'll try to explain why...
To even attempt to do this you need to create a relationship of foreign key to composite key.
ie you need to link the (events.user_id and deleted_at) to (user.id and delete_at). You change one, it'll update the other.
First you will need to add a default rule to your deleted_at columns, as you can not link on null values.
So add to your migrations for both tables...
$table->softDeletes()->default('0000-00-00 00:00:00');
Add to your user table a unique key using 'id' and 'deleted_at'
Schema::table('users; function($table) {
$table->unique(array('id','deleted_at'))
});
Then in the events table create a foreign key like so (links to the unique key)
Schema::table('events; function($table) {
$table->foreign(array('user_id','deleted_at'),'events_deleted_at_foreign_key')->
}->references(array('id','deleted_at'))->on('users')->onUpdate('CASCADE'));
Run this, you should now find if you soft delete your user, it will soft delete its' events.
However if you now try to soft delete an event, it will fail on the foreign key restraint. Why you might ask!?
Well what you're doing is creating a Parent Child relationship using id,deleted_at in both tables. Updating the parent, will update the child. And the relationship is unbroken. However if you Update the child, the relationship is now broken, leaving the child as an orphan in the table. This fails the foreign key restraint.
Sooo a long winded answer, but hopefully a good explanation of why what you're trying to do won't work and save you a whole lot of time trying to do this with ON UPDATE CASCADE. Either get in to the TRIGGERS, and TRIGGER a function to handle what you're trying to do, or handle it in your application. Personally I'd do it with TRIGGERS so the database remains it's own entity and not having to rely on anything to keep data integrity.
delimiter //
CREATE TRIGGER soft_delete_child AFTER UPDATE ON db.users FOR EACH ROW
BEGIN
IF NEW.deleted_at <> OLD.deleted_at THEN
UPDATE events SET deleted_at=NEW.deleted_at WHERE events.user_id=NEW.id;
END IF;
END;
//
delimiter ;

Related

Update then delete child table's value on deleting parent record Laravel

I have two tables Order and OrderItem where OrderItem has the order_id as foreign key from Orders table. I have used laravel relationship in each of their model. Upon deleting a record from Order table which has relation in the OrderItem, I want to update a column name "Cancel" to true in OrderItem table and then soft delete the record.
I only know the manual method where I find the record by id, then update and soft delete it. Can anyone help me with shorter and easier method? Thank you.
I think you're mean is soft delete.
you can see this document.

spring-data-jpa Avoid to delete Parent entity if there are child entities

I have a relationship Invoice - InvoiceLine, and I want to avoid to delete an Invoice is there are InvoiceLines...
I would like to know which relationship is the best:
ALL ,
DETACH,
MERGE,
PERSIST,
REFRESH,
REMOVE
It almost doesn't matter.
As long as you don't use REMOVE and have an actual foreign key relationship between Invoice and InvoiceLine.
Without the REMOVE cascade deleting an Invoice won't touch the InvoiceLines. Which in turn will trigger the foreign key to prevent the operation.

is bad habit to don't use foreign in migration laravel?

I am new in laravel. In my tutorial video teacher use foreign in migration but,i can create my relationships without it and use just belongTo and hasMany.When i use foreign can not delete one post easily (error is you can not delete because parent foreign has child ......).
my question is my way is good or not? and why?
Thank you all
Your way is good but I think foreign keys are better. Had you not had that foreign key, you would have deleted the post but all that post's children (referred to as orphans because they no longer have a parent) would have stuck around. In order to get around the foreign key error, you would need to first delete all the children for that post, and then delete the post.
The good news is foreign keys can also do this for you so you don't need to worry about keeping track of all the children. When you setup the foreign key, if you add the on delete cascade clause, when deleting the post, the database would automatically remove all of the posts's children for you and deleting a post without first deleting the children would no longer result in an error.
If it's your preference to keep the children around even when the post is deleted, you can use on delete set null instead which would simply set the children's foreign key to null rather than delete the record.
This is all useful for enforcing data integrity (databases should contain only accurate and valid data).
The answer really is not 'is this good practice in Laravel' so much as 'is this good practice for database management'.
There are many articles on the topic as to the good and bad side of using foreign keys. Here is a good explanation on the DBA stack exchange
https://dba.stackexchange.com/questions/168590/not-using-foreign-key-constraints-in-real-practice-is-it-ok
My personal preference is to use them to maintain data integrity. The real power comes in adding cascading deletes to the relationship (if applicable to your design).
It really comes down to how good you want your database to be.The main reasons to use foreign keys in your database are
To prevent actions that would destroy links between your tables
This would prevent the invalid data from being inserted to the foreign key column as it has to point to a existing value
Also defining foreign keys makes your query faster depending on database I don't know the exact milliseconds but if I find it out I will post it.
Well from the laravel point of view the way you do is a better way as this is how one of the main teacher of the Laravel(Jeffrey Way) teaches in the getting started with laravel series.
Foreign Keys are the way to define relationship between tables in your database whereas Laravel belongsTo() or hasMany() is a way to define relationship between tables in Laravel

Foreign key, or no foreign key? Defining Laravel relationships

What is the difference between defining a foreign key VS just creating an integer column named user_id?
// create_posts migrations
$table->integer('user_id')->unsigned();
// vs
$table->foreign('user_id')->references('id')->on('users');
Can they be used interchangeably? What purpose do each one serve? Which is considered a best practice, first or second definition?
Edit
The command $post->user() will work either ways, so what advantages does usage of a foreign key bring?
$table->integer('user_id')->unsigned();
// Above command is creating a column in database and it is required to have the required table structure
$table->foreign('user_id')->references('id')->on('users');
// Above command is creating foreign key index and making reference to id in users table.
As you can see from command explanations they can't be interchangeable, you need first command to have second command without first second command would complain.
Best practise is to use both of them together.
Few of advantages are listed below:
You can implement cascade update/delete.
Database level validation that only valid values of user_id is recorded ( to avoid some one entering 999999 which might be invalid or non existing user_id).
Above two are main advantages and you can express multiple scenarios how above two can be life saviour.
Let's say in post table by human error or bug in script makers user_id = 9999. What you think $post->user() will do?
Unless you can have a post without any reference to user you can see there could be multiple logical issue you may find if foreign keys are not used.
Think of foreign keys as enforcing relations and taking care of post if user is removed / deleted from db.
No, They can't be used interchangeably and each one has its usage. Use index when you want to define index on column, means database index, see here. But when you define a foreign key it set a index to that column (for searching, ...) and also make a relation between user_id and id column in user table, so if there is a user by id 10, then you can use user_id = 10 on another table. Also it has another benefits such as making sure your data are integrated. For example you can't delete user by id 10 if there is article that belongs to this user. For more information see this.
The first line, will only create a user_id column not something special,
while the other line will create a column as a foreign key which will be tightly coupled with id column of users table, this will create some limitations.
read about foreign key reference
For the best practices I always use:
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
Don't mix the definition of index with foreign key, they don't mean the same.

Using LINQ to delete child records automatically

I am somewhat new to LINQ and have a quick question regarding deleting.
Say, for example I have 2 tables, Orders and OrderItems. Using LINQ, I can easily create a new child record by using
order.Items.Add(new OrderItem());
and this will create the child record in the database and update its foreign key to the orderId. This is great, I like it! However when I want to remove a child record
order.Items.Remove(orderItem);
I get an error when I sumbit the changes (because its not actually deleting the child row (order item), just removing the foreign keyId). Is it possible to do this the way I would like to? I don't want to have to create a whole bunch of repositories and if ladders to delete all child rows for a large database.
Thanks in advance.
E
You can achieve that in the DB itself by configuring the Foreign key relationship to delete child records on deletion of the parent's key.
Note that this is transparent to Linq2SQL and it will not be aware of it, so it's best to make sure you do not keep the datacontexts around after that, since the OrderItem objects will still be present.
Set ON DELETE CASCADE for the table in question which will let the SQL Server handle this for you.

Resources