laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Eloquent Collection should allow using relationships #2180

Open gms8994 opened 4 years ago

gms8994 commented 4 years ago

Given $modelCollection = Model::get(), it would be nice if I could then $modelCollection->relation()->delete() (or any other thing that $model->relation() gives me the ability to do). This would prevent code like

foreach ($modelCollection as $model) {
    $model->relation()->delete();
}

from generating thousands of individual deletes, where the collection version could generate a single delete for all values.

Of course this would only work if the collection contains a single model class.

mesiarm commented 3 years ago

some HighOrderProxy would be needed there.

akbarjimi commented 3 years ago

No need to do it in a loop Just pluck the id of $modelCollection like this

$ids = $modelCollection->pluck('id')->toArray();

then delete the relation

RelatedModel::whereIn($ids)->delete();