{"id":15169482,"url":"https://github.com/yii2tech/ar-softdelete","last_synced_at":"2025-10-01T02:31:18.063Z","repository":{"id":36236518,"uuid":"40540854","full_name":"yii2tech/ar-softdelete","owner":"yii2tech","description":"Soft delete behavior for ActiveRecord","archived":true,"fork":false,"pushed_at":"2020-04-20T17:24:06.000Z","size":61,"stargazers_count":206,"open_issues_count":0,"forks_count":47,"subscribers_count":18,"default_branch":"master","last_synced_at":"2024-09-22T22:01:54.928Z","etag":null,"topics":["activerecord","soft-delete","soft-deletes","yii","yii2","yii2-extension"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yii2tech.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":["klimov-paul"],"patreon":"klimov_paul"}},"created_at":"2015-08-11T12:39:21.000Z","updated_at":"2024-09-11T15:37:06.000Z","dependencies_parsed_at":"2022-09-09T11:41:16.473Z","dependency_job_id":null,"html_url":"https://github.com/yii2tech/ar-softdelete","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Far-softdelete","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Far-softdelete/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Far-softdelete/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Far-softdelete/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yii2tech","download_url":"https://codeload.github.com/yii2tech/ar-softdelete/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":219875269,"owners_count":16554660,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["activerecord","soft-delete","soft-deletes","yii","yii2","yii2-extension"],"created_at":"2024-09-27T07:01:53.585Z","updated_at":"2025-10-01T02:31:12.793Z","avatar_url":"https://github.com/yii2tech.png","language":"PHP","funding_links":["https://github.com/sponsors/klimov-paul","https://patreon.com/klimov_paul"],"categories":["Behaviors"],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://github.com/yii2tech\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://avatars2.githubusercontent.com/u/12951949\" height=\"100px\"\u003e\n    \u003c/a\u003e\n    \u003ch1 align=\"center\"\u003eActiveRecord Soft Delete Extension for Yii2\u003c/h1\u003e\n    \u003cbr\u003e\n\u003c/p\u003e\n\nThis extension provides support for ActiveRecord soft delete.\n\nFor license information check the [LICENSE](LICENSE.md)-file.\n\n[![Latest Stable Version](https://img.shields.io/packagist/v/yii2tech/ar-softdelete.svg)](https://packagist.org/packages/yii2tech/ar-softdelete)\n[![Total Downloads](https://img.shields.io/packagist/dt/yii2tech/ar-softdelete.svg)](https://packagist.org/packages/yii2tech/ar-softdelete)\n[![Build Status](https://travis-ci.org/yii2tech/ar-softdelete.svg?branch=master)](https://travis-ci.org/yii2tech/ar-softdelete)\n\n\nInstallation\n------------\n\nThe preferred way to install this extension is through [composer](http://getcomposer.org/download/).\n\nEither run\n\n```\nphp composer.phar require --prefer-dist yii2tech/ar-softdelete\n```\n\nor add\n\n```json\n\"yii2tech/ar-softdelete\": \"*\"\n```\n\nto the require section of your composer.json.\n\n\nUsage\n-----\n\nThis extension provides support for so called \"soft\" deletion of the ActiveRecord, which means record is not deleted\nfrom database, but marked with some flag or status, which indicates it is no longer active, instead.\n\nThis extension provides [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior]] ActiveRecord behavior for such solution\nsupport in Yii2. You may attach it to your model class in the following way:\n\n```php\n\u003c?php\n\nuse yii\\db\\ActiveRecord;\nuse yii2tech\\ar\\softdelete\\SoftDeleteBehavior;\n\nclass Item extends ActiveRecord\n{\n    public function behaviors()\n    {\n        return [\n            'softDeleteBehavior' =\u003e [\n                'class' =\u003e SoftDeleteBehavior::className(),\n                'softDeleteAttributeValues' =\u003e [\n                    'isDeleted' =\u003e true\n                ],\n            ],\n        ];\n    }\n}\n```\n\nThere are 2 ways of \"soft\" delete applying:\n - using `softDelete()` separated method\n - mutating regular `delete()` method\n\nUsage of `softDelete()` is recommended, since it allows marking the record as \"deleted\", while leaving regular `delete()`\nmethod intact, which allows you to perform \"hard\" delete if necessary. For example:\n\n```php\n\u003c?php\n\n$id = 17;\n$item = Item::findOne($id);\n$item-\u003esoftDelete(); // mark record as \"deleted\"\n\n$item = Item::findOne($id);\nvar_dump($item-\u003eisDeleted); // outputs \"true\"\n\n$item-\u003edelete(); // perform actual deleting of the record\n$item = Item::findOne($id);\nvar_dump($item); // outputs \"null\"\n```\n\nHowever, you may want to mutate regular ActiveRecord `delete()` method in the way it performs \"soft\" deleting instead\nof actual removing of the record. It is a common solution in such cases as applying \"soft\" delete functionality for\nexisting code. For such functionality you should enable [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::$replaceRegularDelete]]\noption in behavior configuration:\n\n```php\n\u003c?php\n\nuse yii\\db\\ActiveRecord;\nuse yii2tech\\ar\\softdelete\\SoftDeleteBehavior;\n\nclass Item extends ActiveRecord\n{\n    public function behaviors()\n    {\n        return [\n            'softDeleteBehavior' =\u003e [\n                'class' =\u003e SoftDeleteBehavior::className(),\n                'softDeleteAttributeValues' =\u003e [\n                    'isDeleted' =\u003e true\n                ],\n                'replaceRegularDelete' =\u003e true // mutate native `delete()` method\n            ],\n        ];\n    }\n}\n```\n\nNow invocation of the `delete()` method will mark record as \"deleted\" instead of removing it:\n\n```php\n\u003c?php\n\n$id = 17;\n$item = Item::findOne($id);\n$item-\u003edelete(); // no record removal, mark record as \"deleted\" instead\n\n$item = Item::findOne($id);\nvar_dump($item-\u003eisDeleted); // outputs \"true\"\n```\n\n**Heads up!** In case you mutate regular ActiveRecord `delete()` method, it will be unable to function with ActiveRecord\ntransactions feature, e.g. scenarios with [[\\yii\\db\\ActiveRecord::OP_DELETE]] or [[\\yii\\db\\ActiveRecord::OP_ALL]]\ntransaction levels:\n\n```php\n\u003c?php\n\nuse yii\\db\\ActiveRecord;\nuse yii2tech\\ar\\softdelete\\SoftDeleteBehavior;\n\nclass Item extends ActiveRecord\n{\n    public function behaviors()\n    {\n        return [\n            'softDeleteBehavior' =\u003e [\n                'class' =\u003e SoftDeleteBehavior::className(),\n                'replaceRegularDelete' =\u003e true // mutate native `delete()` method\n            ],\n        ];\n    }\n\n    public function transactions()\n    {\n        return [\n            'some' =\u003e self::OP_DELETE,\n        ];\n    }\n}\n\n$item = Item::findOne($id);\n$item-\u003esetScenario('some');\n$item-\u003edelete(); // nothing happens!\n```\n\n\n## Querying \"soft\" deleted records \u003cspan id=\"querying-soft-deleted-records\"\u003e\u003c/span\u003e\n\nObviously, in order to find only \"deleted\" or only \"active\" records you should add corresponding condition to your search query:\n\n```php\n\u003c?php\n\n// returns only not \"deleted\" records\n$notDeletedItems = Item::find()\n    -\u003ewhere(['isDeleted' =\u003e false])\n    -\u003eall();\n\n// returns \"deleted\" records\n$deletedItems = Item::find()\n    -\u003ewhere(['isDeleted' =\u003e true])\n    -\u003eall();\n```\n\nHowever, you can use [[yii2tech\\ar\\softdelete\\SoftDeleteQueryBehavior]] to facilitate composition of such queries.\nThe easiest way to apply this behavior is its manual attachment to the query instance at [[\\yii\\db\\BaseActiveRecord::find()]]\nmethod. For example:\n\n```php\n\u003c?php\n\nuse yii\\db\\ActiveRecord;\nuse yii2tech\\ar\\softdelete\\SoftDeleteBehavior;\nuse yii2tech\\ar\\softdelete\\SoftDeleteQueryBehavior;\n\nclass Item extends ActiveRecord\n{\n    // ...\n    public function behaviors()\n    {\n        return [\n            'softDeleteBehavior' =\u003e [\n                'class' =\u003e SoftDeleteBehavior::className(),\n                // ...\n            ],\n        ];\n    }\n\n    /**\n     * @return \\yii\\db\\ActiveQuery|SoftDeleteQueryBehavior\n     */\n    public static function find()\n    {\n        $query = parent::find();\n        $query-\u003eattachBehavior('softDelete', SoftDeleteQueryBehavior::className());\n        return $query;\n    }\n}\n```\n\nIn case you already define custom query class for your active record, you can move behavior attachment there.\nFor example:\n\n```php\n\u003c?php\n\nuse yii\\db\\ActiveRecord;\nuse yii2tech\\ar\\softdelete\\SoftDeleteBehavior;\nuse yii2tech\\ar\\softdelete\\SoftDeleteQueryBehavior;\n\nclass Item extends ActiveRecord\n{\n    // ...\n    public function behaviors()\n    {\n        return [\n            'softDeleteBehavior' =\u003e [\n                'class' =\u003e SoftDeleteBehavior::className(),\n                // ...\n            ],\n        ];\n    }\n\n    /**\n     * @return ItemQuery|SoftDeleteQueryBehavior\n     */\n    public static function find()\n    {\n        return new ItemQuery(get_called_class());\n    }\n}\n\nclass ItemQuery extends \\yii\\db\\ActiveQuery\n{\n    public function behaviors()\n    {\n        return [\n            'softDelete' =\u003e [\n                'class' =\u003e SoftDeleteQueryBehavior::className(),\n            ],\n        ];\n    }\n}\n```\n\nOnce being attached [[yii2tech\\ar\\softdelete\\SoftDeleteQueryBehavior]] provides named scopes for the records filtering using\n\"soft\" deleted criteria. For example:\n\n```php\n\u003c?php\n\n// Find all \"deleted\" records:\n$deletedItems = Item::find()-\u003edeleted()-\u003eall();\n\n// Find all \"active\" records:\n$notDeletedItems = Item::find()-\u003enotDeleted()-\u003eall();\n\n// find all comments for not \"deleted\" items:\n$comments = Comment::find()\n    -\u003einnerJoinWith(['item' =\u003e function ($query) {\n        $query-\u003enotDeleted();\n    }])\n    -\u003eall();\n```\n\nYou may easily create listing filter for \"deleted\" records using `filterDeleted()` method:\n\n```php\n\u003c?php\n\n// Filter records by \"soft\" deleted criteria:\n$items = Item::find()\n    -\u003efilterDeleted(Yii::$app-\u003erequest-\u003eget('filter_deleted'))\n    -\u003eall();\n```\n\nThis method applies `notDeleted()` scope on empty filter value, `deleted()` - on positive filter value, and no scope (e.g.\nshow both \"deleted\" and \"active\" records) on negative (zero) value.\n\n\u003e Note: [[yii2tech\\ar\\softdelete\\SoftDeleteQueryBehavior]] has been designed to properly handle joins and avoid ambiguous\n  column errors, however, there still can be cases, which it will be unable to handle properly. Be prepared to specify\n  \"soft deleted\" conditions manually in case you are writing complex query, involving several tables with \"soft delete\" feature.\n\nBy default [[yii2tech\\ar\\softdelete\\SoftDeleteQueryBehavior]] composes filter criteria for its scopes using the information from\n[[yii2tech\\ar\\softdelete\\SoftDeleteBehavior::$softDeleteAttributeValues]]. Thus you may need to manually configure filter conditions\nin case you are using sophisticated logic for \"soft\" deleted records marking. For example:\n\n```php\n\u003c?php\n\nuse yii\\db\\ActiveRecord;\nuse yii2tech\\ar\\softdelete\\SoftDeleteBehavior;\nuse yii2tech\\ar\\softdelete\\SoftDeleteQueryBehavior;\n\nclass Item extends ActiveRecord\n{\n    // ...\n    public function behaviors()\n    {\n        return [\n            'softDeleteBehavior' =\u003e [\n                'class' =\u003e SoftDeleteBehavior::className(),\n                'softDeleteAttributeValues' =\u003e [\n                    'statusId' =\u003e 'deleted',\n                ],\n            ],\n        ];\n    }\n\n    /**\n     * @return \\yii\\db\\ActiveQuery|SoftDeleteQueryBehavior\n     */\n    public static function find()\n    {\n        $query = parent::find();\n        \n        $query-\u003eattachBehavior('softDelete', [\n            'class' =\u003e SoftDeleteQueryBehavior::className(),\n            'deletedCondition' =\u003e [\n                'statusId' =\u003e 'deleted',\n            ],\n            'notDeletedCondition' =\u003e [\n                'statusId' =\u003e 'active',\n            ],\n        ]);\n        \n        return $query;\n    }\n}\n```\n\n\u003e Tip: you may apply a condition, which filters \"not deleted\" records, to the ActiveQuery as default scope, overriding\n  `find()` method. Also remember, that you may reset such default scope using `onCondition()`  and `where()` methods\n  with empty condition.\n\n```php\n\u003c?php\n\nuse yii\\db\\ActiveRecord;\nuse yii2tech\\ar\\softdelete\\SoftDeleteBehavior;\nuse yii2tech\\ar\\softdelete\\SoftDeleteQueryBehavior;\n\nclass Item extends ActiveRecord\n{\n    public function behaviors()\n    {\n        return [\n            'softDeleteBehavior' =\u003e [\n                'class' =\u003e SoftDeleteBehavior::className(),\n                'softDeleteAttributeValues' =\u003e [\n                    'isDeleted' =\u003e true\n                ],\n            ],\n        ];\n    }\n\n    /**\n     * @return \\yii\\db\\ActiveQuery|SoftDeleteQueryBehavior\n     */\n    public static function find()\n    {\n        $query = parent::find();\n        \n        $query-\u003eattachBehavior('softDelete', SoftDeleteQueryBehavior::className());\n        \n        return $query-\u003enotDeleted();\n    }\n}\n\n$notDeletedItems = Item::find()-\u003eall(); // returns only not \"deleted\" records\n\n$allItems = Item::find()\n    -\u003eonCondition([]) // resets \"not deleted\" scope for relational databases\n    -\u003eall(); // returns all records\n\n$allItems = Item::find()\n    -\u003ewhere([]) // resets \"not deleted\" scope for NOSQL databases\n    -\u003eall(); // returns all records\n```\n\n\n## Smart deletion \u003cspan id=\"smart-deletion\"\u003e\u003c/span\u003e\n\nUsually \"soft\" deleting feature is used to prevent the database history loss, ensuring data, which been in use and\nperhaps have a references or dependencies, is kept in the system. However sometimes actual deleting is allowed for\nsuch data as well.\nFor example: usually user account records should not be deleted but only marked as \"inactive\", however if you browse\nthrough users list and found accounts, which has been registered long ago, but don't have at least single log-in in the\nsystem, these records have no value for the history and can be removed from database to save disk space.\n\nYou can make \"soft\" deletion to be \"smart\" and detect, if the record can be removed from the database or only marked as \"deleted\".\nThis can be done via [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::$allowDeleteCallback]]. For example:\n\n```php\n\u003c?php\n \nuse yii\\db\\ActiveRecord;\nuse yii2tech\\ar\\softdelete\\SoftDeleteBehavior;\n\nclass User extends ActiveRecord\n{\n    public function behaviors()\n    {\n        return [\n            'softDeleteBehavior' =\u003e [\n                'class' =\u003e SoftDeleteBehavior::className(),\n                'softDeleteAttributeValues' =\u003e [\n                    'isDeleted' =\u003e true\n                ],\n                'allowDeleteCallback' =\u003e function ($user) {\n                    return $user-\u003elastLoginDate === null; // allow delete user, if he has never logged in\n                }\n            ],\n        ];\n    }\n}\n\n$user = User::find()-\u003ewhere(['lastLoginDate' =\u003e null])-\u003elimit(1)-\u003eone();\n$user-\u003esoftDelete(); // removes the record!!!\n\n$user = User::find()-\u003ewhere(['not' =\u003e['lastLoginDate' =\u003e null]])-\u003elimit(1)-\u003eone();\n$user-\u003esoftDelete(); // marks record as \"deleted\"\n```\n\n[[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::$allowDeleteCallback]] logic is applied in case [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::$replaceRegularDelete]]\nis enabled as well.\n\n\n## Handling foreign key constraints \u003cspan id=\"handling-foreign-key-constraints\"\u003e\u003c/span\u003e\n\nIn case of usage of the relational database, which supports foreign keys, like MySQL, PostgreSQL etc., \"soft\" deletion\nis widely used for keeping foreign keys consistence. For example: if user performs a purchase at the online shop, information\nabout this purchase should remain in the system for the future bookkeeping. The DDL for such data structure may look like\nfollowing one:\n\n```sql\nCREATE TABLE `Customer`\n(\n   `id` integer NOT NULL AUTO_INCREMENT,\n   `name` varchar(64) NOT NULL,\n   `address` varchar(64) NOT NULL,\n   `phone` varchar(20) NOT NULL,\n    PRIMARY KEY (`id`)\n) ENGINE InnoDB;\n\nCREATE TABLE `Purchase`\n(\n   `id` integer NOT NULL AUTO_INCREMENT,\n   `customerId` integer NOT NULL,\n   `itemId` integer NOT NULL,\n   `amount` integer NOT NULL,\n    PRIMARY KEY (`id`)\n    FOREIGN KEY (`customerId`) REFERENCES `Customer` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,\n    FOREIGN KEY (`itemId`) REFERENCES `Item` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,\n) ENGINE InnoDB;\n```\n\nThus, while set up a foreign key from 'purchase' to 'user', 'ON DELETE RESTRICT' mode is used. So on attempt to delete\na user record, which have at least one purchase, a database error will occur. However, if user record have no external\nreference, it can be deleted.\n\nUsage of [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::$allowDeleteCallback]] for such use case is not very practical.\nIt will require performing extra queries to determine, if external references exist or not, eliminating the benefits of\nthe foreign keys database feature.\n\nMethod [\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::safeDelete()]] attempts to invoke regular [[\\yii\\db\\BaseActiveRecord::delete()]]\nmethod, and, if it fails with exception, falls back to [[yii2tech\\ar\\softdelete\\SoftDeleteBehavior::softDelete()]].\n\n```php\n\u003c?php\n\n// if there is a foreign key reference :\n$customer = Customer::findOne(15);\nvar_dump(count($customer-\u003epurchases)); // outputs; \"1\"\n$customer-\u003esafeDelete(); // performs \"soft\" delete!\nvar_dump($customer-\u003eisDeleted) // outputs: \"true\"\n\n// if there is NO foreign key reference :\n$customer = Customer::findOne(53);\nvar_dump(count($customer-\u003epurchases)); // outputs; \"0\"\n$customer-\u003esafeDelete(); // performs actual delete!\n$customer = Customer::findOne(53);\nvar_dump($customer); // outputs: \"null\"\n```\n\nBy default `safeDelete()` method catches [[\\yii\\db\\IntegrityException]] exception, which means soft deleting will be\nperformed on foreign constraint violation DB exception. You may specify another exception class here to customize fallback\nerror level. For example: usage of [[\\Throwable]] will cause soft-delete fallback on any error during regular deleting.\n\n\n## Record restoration \u003cspan id=\"record-restoration\"\u003e\u003c/span\u003e\n\nAt some point you may want to \"restore\" records, which have been marked as \"deleted\" in the past.\nYou may use `restore()` method for this:\n\n```php\n\u003c?php\n\n$id = 17;\n$item = Item::findOne($id);\n$item-\u003esoftDelete(); // mark record as \"deleted\"\n\n$item = Item::findOne($id);\n$item-\u003erestore(); // restore record\nvar_dump($item-\u003eisDeleted); // outputs \"false\"\n```\n\nBy default attribute values, which should be applied for record restoration are automatically detected from [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::$softDeleteAttributeValues]],\nhowever it is better you specify them explicitly via [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::$restoreAttributeValues]].\n\n\u003e Tip: if you enable [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::$useRestoreAttributeValuesAsDefaults]], attribute values,\n  which marks restored record, will be automatically applied at new record insertion.\n\n\n## Events \u003cspan id=\"events\"\u003e\u003c/span\u003e\n\nBy default [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::softDelete()]] triggers [[\\yii\\db\\BaseActiveRecord::EVENT_BEFORE_DELETE]]\nand [[\\yii\\db\\BaseActiveRecord::EVENT_AFTER_DELETE]] events in the same way they are triggered at regular `delete()`.\n\nAlso [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior]] triggers several additional events in the scope of the owner ActiveRecord:\n\n - [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::EVENT_BEFORE_SOFT_DELETE]] - triggered before \"soft\" delete is made.\n - [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::EVENT_AFTER_SOFT_DELETE]] - triggered after \"soft\" delete is made.\n - [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::EVENT_BEFORE_RESTORE]] - triggered before record is restored from \"deleted\" state.\n - [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::EVENT_AFTER_RESTORE]] - triggered after record is restored from \"deleted\" state.\n\nYou may attach the event handlers for these events to your ActiveRecord object:\n\n```php\n\u003c?php\n\n$item = Item::findOne($id);\n$item-\u003eon(SoftDeleteBehavior::EVENT_BEFORE_SOFT_DELETE, function($event) {\n    $event-\u003eisValid = false; // prevent \"soft\" delete to be performed\n});\n```\n\nYou may also handle these events inside your ActiveRecord class by declaring the corresponding methods:\n\n```php\n\u003c?php\n\nuse yii\\db\\ActiveRecord;\nuse yii2tech\\ar\\softdelete\\SoftDeleteBehavior;\n\nclass Item extends ActiveRecord\n{\n    public function behaviors()\n    {\n        return [\n            'softDeleteBehavior' =\u003e [\n                'class' =\u003e SoftDeleteBehavior::className(),\n                // ...\n            ],\n        ];\n    }\n\n    public function beforeSoftDelete()\n    {\n        $this-\u003edeletedAt = time(); // log the deletion date\n        return true;\n    }\n\n    public function beforeRestore()\n    {\n        return $this-\u003edeletedAt \u003e (time() - 3600); // allow restoration only for the records, being deleted during last hour\n    }\n}\n```\n\n\n## Transactional operations \u003cspan id=\"transactional-operations\"\u003e\u003c/span\u003e\n\nYou can explicitly enclose [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::softDelete()]] method call in a transactional block, like following:\n\n```php\n\u003c?php\n\n$item = Item::findOne($id);\n\n$transaction = $item-\u003egetDb()-\u003ebeginTransaction();\ntry {\n    $item-\u003esoftDelete();\n    // ...other DB operations...\n    $transaction-\u003ecommit();\n} catch (\\Exception $e) { // PHP \u003c 7.0\n    $transaction-\u003erollBack();\n    throw $e;\n} catch (\\Throwable $e) { // PHP \u003e= 7.0\n    $transaction-\u003erollBack();\n    throw $e;\n}\n```\n\nAlternatively you can use [[\\yii\\db\\ActiveRecord::transactions()]] method to specify the list of operations, which should be performed inside the transaction block.\nMethod [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::softDelete()]] responds both to [[\\yii\\db\\ActiveRecord::OP_UPDATE]] and [[\\yii\\db\\ActiveRecord::OP_DELETE]].\nIn case current model scenario includes at least of those constants, soft-delete will be performed inside the transaction block.\n\n\u003e Note: method [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::safeDelete()]] uses its own internal transaction logic, which may\n  conflict with automatic transactional operations. Make sure you do not run this method in the scenario, which is affected by\n  [[\\yii\\db\\ActiveRecord::transactions()]].\n\n\n## Optimistic locks \u003cspan id=\"optimistic-locks\"\u003e\u003c/span\u003e\n\nSoft-delete supports optimistic lock in the same way as regular [[\\yii\\db\\ActiveRecord::save()]] method.\nIn case you have specified version attribute via [[\\yii\\db\\ActiveRecord::optimisticLock()]], [[\\yii2tech\\ar\\softdelete\\SoftDeleteBehavior::softDelete()]]\nwill throw [[\\yii\\db\\StaleObjectException]] exception in case of version number outdated.\nFor example, in case you ActiveRecord is defined as following:\n\n```php\n\u003c?php\n\nuse yii\\db\\ActiveRecord;\nuse yii2tech\\ar\\softdelete\\SoftDeleteBehavior;\n\nclass Item extends ActiveRecord\n{\n    /**\n     * {@inheritdoc}\n     */\n    public function behaviors()\n    {\n        return [\n            'softDelete' =\u003e [\n                'class' =\u003e SoftDeleteBehavior::className(),\n                'softDeleteAttributeValues' =\u003e [\n                    'isDeleted' =\u003e true\n                ],\n            ],\n        ];\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function optimisticLock()\n    {\n        return 'version';\n    }\n}\n```\n\nYou can create delete link in following way:\n\n```php\n\u003c?php\nuse yii\\helpers\\Html;\n\n/* @var $model Item */\n?\u003e\n...\n\u003c?= Html::a('delete', ['delete', 'id' =\u003e $model-\u003eid, 'version' =\u003e $model-\u003eversion], ['data-method' =\u003e 'post']) ?\u003e\n...\n```\n\nThen you can catch [[\\yii\\db\\StaleObjectException]] exception inside controller action code to resolve the conflict:\n\n```php\n\u003c?php\n\nuse yii\\db\\StaleObjectException;\nuse yii\\web\\Controller;\n\nclass ItemController extends Controller\n{\n    public function delete($id, $version)\n    {\n        $model = $this-\u003efindModel($id);\n        $model-\u003eversion = $version;\n        \n        try {\n            $model-\u003esoftDelete();\n            return $this-\u003eredirect(['index']);\n        } catch (StaleObjectException $e) {\n            // logic to resolve the conflict\n        }\n    }\n    \n    // ...\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyii2tech%2Far-softdelete","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyii2tech%2Far-softdelete","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyii2tech%2Far-softdelete/lists"}