Salta ai contenuti
PHP Ecosystem
Explore

Soft Delete

Questi contenuti non sono ancora disponibili nella tua lingua.

Soft deletion and restoration for Yii2 ActiveRecord

Mark records as deleted without losing them, and restore them when needed

Feature Overview

Install the package with Composer:

Terminal window
composer require yii2-extensions/soft-delete:^0.1

Applications on Yii 2.0 need a Bower asset source such as Asset Packagist. The Installation Guide covers it, together with Yii 22 and local checkouts.

A billing schema: customer has a country and a nullable deleted_at timestamp. invoice references it through a customer_id foreign key and has a status and an is_void boolean that defaults to false.

use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii2\extensions\softdelete\DeleteBehavior;
use yii2\extensions\softdelete\ScopedQuery;
final class Customer extends ActiveRecord
{
public function behaviors(): array
{
return [
'softDelete' => [
'class' => DeleteBehavior::class,
// Stamp the deletion time. restore() writes null back, and the scopes test IS [NOT] NULL.
'softDeleteAttributeValues' => ['deleted_at' => static fn(): int => time()],
],
];
}
// Hide deleted customers by default: findOne(), relations, joins and eager loading all start here.
public static function find(): ScopedQuery
{
return (new ScopedQuery(self::class))->notDeleted();
}
public function getInvoices(): ActiveQuery
{
return $this->hasMany(Invoice::class, ['customer_id' => 'id']);
}
}
final class Invoice extends ActiveRecord
{
public function behaviors(): array
{
return [
'softDelete' => [
'class' => DeleteBehavior::class,
'softDeleteAttributeValues' => ['is_void' => true],
// A draft never reached the ledger, so softDelete() removes its row instead of marking it.
'allowDeleteCallback' => static fn(Invoice $invoice): bool => $invoice->status === 'draft',
],
];
}
public static function find(): ScopedQuery
{
return (new ScopedQuery(self::class))->notDeleted();
}
// A paid invoice cannot be voided: softDelete() returns false and writes nothing.
public function beforeSoftDelete(): bool
{
return $this->status !== 'paid';
}
}

The scopes follow each query through aliases, joins and filters:

// Active customers with an overdue invoice. Each table keeps its scope under its own alias,
// and voided invoices are excluded inside the JOIN, not after it.
$debtors = Customer::find()
->alias('c')
->innerJoinWith('invoices i')
->andWhere(['i.status' => 'overdue'])
->all();
// Removes the row when nothing references it. While an invoice still does, the foreign key
// rejects the delete and the customer is marked as deleted instead.
$customer->safeDelete();
// One call per invoice, three outcomes: a draft is removed, a paid one is refused, any other is voided.
$invoice->softDelete();
// Switch scope without losing the other filters.
$deleted = Customer::find()
->deleted()
->andWhere(['country' => 'CL'])
->all();
$total = Customer::find()
->withDeleted()
->count();
// Bring a customer back.
Customer::find()
->deleted()
->andWhere(['id' => $id])
->one()
?->restore();

filterDeleted() maps a request value to a scope, and writes honor optimistic locking; the Usage Examples show both. The Configuration Guide details transactions and the foreign-key fallback.

Practical guides for configuring soft deletion, querying records, and running the test suite.

The guides and the API reference generated from the PHPDoc in src/ are available at https://yii2-framework.github.io/docs/extensions/soft-delete/.

AI agents: read the documentation index and fetch the Markdown version of a page by appending index.md to its URL. The AI agents guide covers skill installation, client setup and verification.

The hosted documentation covers Yii 22.0. If it does not match the installed revision or is unavailable, use the repository guides, the skill source, the source PHPDoc and the changelog.

Follow on X Follow on Facebook Join our Subreddit Join on Telegram

Inspired by yii2tech/ar-softdelete by Paul Klimov.

License