Skip to content

Commit

Permalink
improve memory consumption (#74)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidcorreia authored Jan 6, 2025
1 parent 467aa81 commit d5d78b9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ class Post extends Model

protected $dates = ['deleted_at'];

protected $fetchMethod = 'get'; // get, cursor, lazy or chunk
// protected $chunkSize = 500;

public function comments()
{
return $this->hasMany(Comment::class);
Expand Down
17 changes: 16 additions & 1 deletion src/CascadeSoftDeletes.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,23 @@ protected function cascadeSoftDeletes($relationship)
{
$delete = $this->forceDeleting ? 'forceDelete' : 'delete';

foreach ($this->{$relationship}()->get() as $model) {
$cb = function($model) use ($delete) {
isset($model->pivot) ? $model->pivot->{$delete}() : $model->{$delete}();
};

$this->handleRecords($relationship, $cb);
}

private function handleRecords($relationship, $cb)
{
$fetchMethod = $this->fetchMethod ?? 'get';

if ($fetchMethod == 'chunk') {
$this->{$relationship}()->chunk($this->chunkSize ?? 500, $cb);
} else {
foreach($this->{$relationship}()->$fetchMethod() as $model) {
$cb($model);
}
}
}

Expand Down

0 comments on commit d5d78b9

Please sign in to comment.