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

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.

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.

How to cascade on softdeletes in Laravel4?

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 ;

Magento: How to delete parent object when child reference changes?

Given:
Two custom classes in Magento with a Many-to-One relationship between them.
The child holds a foreign key to the parent.
The database is set to cascade deletes.
There are cases when a child's reference changes to a different parent. In some of those cases, I want to delete the parent in the afterSave method of the child. When I do this, the child itself disappears, since the change of FK to the new parent hasn't been written to the database yet, and the database level cascade kicks in.
How can I arrange for the deletion of the parent object after the write of the new foreign key in the child object?
afterSave triggers before the query has been written to DB, as you've noticed yourself. You need to use *_save_commit_after event. Where asterisk is your Models event_prefix. Create an Observer and listen for this event, that way you can be sure that info in DB has been already updated, and you won't suffer the foreign key effect.

How can I do more than one level of cascading deletes in Linq?

If I have a Customers table linked to an Orders table, and I want to delete a customer and its corresponding orders, then I can do:
dataContext.Orders.DeleteAllOnSubmit(customer.Orders);
dataContext.Customers.DeleteOnSubmit(customer);
...which is great. However, what if I also have an OrderItems table, and I want to delete the order items for each of the orders deleted?
I can see how I could use DeleteAllOnSubmit to cause the deletion of all the order items for a single order, but how can I do it for all the orders?
You might wish to consider using on delete cascade on the foreign key relationship in the database rather then using LINQ to do it. If you wish to use LINQ then
customer.Orders.ForEach(x => x.OrderItems.ForEach(y=> dataContext.OrderItems.Delete(y));
dataContext.Orders.DeleteAllOnSubmit(customer.Orders);
dataContext.Customers.DeleteOnSubmit(customer);
should do it but I haven't tested it.

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