软删除(SoftDelete)¶
This behavior can be used in the following way:
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\SoftDelete;
class Users extends Model
{
const DELETED = 'D';
const NOT_DELETED = 'N';
public $id;
public $name;
public $status;
public function initialize()
{
$this->addBehavior(
new SoftDelete(
array(
'field' => 'status',
'value' => Users::DELETED
)
)
);
}
}
This behavior accepts two options: ‘field’ and ‘value’, ‘field’ determines what field must be updated and ‘value’ the value to be deleted.
Let’s pretend the table ‘users’ has the following data:
mysql> select * from users;
+----+---------+--------+
| id | name | status |
+----+---------+--------+
| 1 | Lana | N |
| 2 | Brandon | N |
+----+---------+--------+
2 rows in set (0.00 sec)
If we delete any of the two records the status will be updated instead of delete the record:
Users::findFirst(2)->delete();
The operation will result in the following data in the table:
mysql> select * from users;
+----+---------+--------+
| id | name | status |
+----+---------+--------+
| 1 | Lana | N |
| 2 | Brandon | D |
+----+---------+--------+
2 rows in set (0.01 sec)
Note that you need to specify the deleted condition in your queries to effectively ignore them as deleted records, this behavior doesn’t support that.