Skip to content

Commit d5d78b9

Browse files
authored
improve memory consumption (#74)
1 parent 467aa81 commit d5d78b9

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ class Post extends Model
3636

3737
protected $dates = ['deleted_at'];
3838

39+
protected $fetchMethod = 'get'; // get, cursor, lazy or chunk
40+
// protected $chunkSize = 500;
41+
3942
public function comments()
4043
{
4144
return $this->hasMany(Comment::class);

src/CascadeSoftDeletes.php

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,23 @@ protected function cascadeSoftDeletes($relationship)
6565
{
6666
$delete = $this->forceDeleting ? 'forceDelete' : 'delete';
6767

68-
foreach ($this->{$relationship}()->get() as $model) {
68+
$cb = function($model) use ($delete) {
6969
isset($model->pivot) ? $model->pivot->{$delete}() : $model->{$delete}();
70+
};
71+
72+
$this->handleRecords($relationship, $cb);
73+
}
74+
75+
private function handleRecords($relationship, $cb)
76+
{
77+
$fetchMethod = $this->fetchMethod ?? 'get';
78+
79+
if ($fetchMethod == 'chunk') {
80+
$this->{$relationship}()->chunk($this->chunkSize ?? 500, $cb);
81+
} else {
82+
foreach($this->{$relationship}()->$fetchMethod() as $model) {
83+
$cb($model);
84+
}
7085
}
7186
}
7287

0 commit comments

Comments
 (0)