Summary
I'm trying to let my model controller delete multiple models (selected by an array of IDs) including their selected related models (selected by an array of relationship names).
Situation
Model
Post
with relationships:- (One-to-Many) with
Comment
model under$post->comments()
- (One-to-Many) with
Image
model under$post->images()
- (Many-to-One) with
User
model under$post->user()
- (One-to-Many) with
- In
PostController
there's thedestroy_multiple
method that handles the deletion, and where I have:- Array
$ids
with IDs ofPost
models to delete (e.g.[1,2,4]
) - Array
$related_models
with relationship names to delete as well (e.g.['user','comments']
but could be a different selection in each call)
- Array
Attempts
1) Iterate and delete:
Post::findMany($ids)->each(function($item) use ($related_models) {
foreach ($related_models as $relation) {
$item->{$relation}()->delete();
}
$item->delete();
});
Problem: All models have to be retrieved first, and for each model, all selected related models have to be deleted. This is a LOT of overhead.
2) Delete related models and models:
// For every selected relationship, delete related models
foreach ($related_models as $relation) {
$class = 'App\\' . studly_case(str_singular($relation));
$class::whereIn('post_id', $ids)->delete();
}
// Delete the models
Post::destroy($ids);
Problem: This only works for the one-to-many relationships and only provided the database columns are named according to the Laravel standard.
Question
What is the most efficient way to do this, while:
- using the defined relationships to ensure the right database naming, columns, etc (as in Attempt 1)
- keeping the performance (without having to retrieve the models) (as in Attempt 2)
- keeping the optionality of choosing the
$ids
and$related_models
?
Notes
- I know that deleting a parent model (
User
in this case) is not very good practice, but it's there for the sake of the question. ;) - Using the database
CASCADE
constraint on the foreign keys of the related models' tables (in the migration) makes it lose the optionality. Related models are now always deleted, and also in other instances besides thedelete_multiple
method.