Object relational mapping - Constraints and validators - Check.php 1.48 KB
Newer Older
hansbrix's avatar
hansbrix committed
1 2 3 4 5 6 7 8 9 10
Doctrine check constraints act as database level constraints as well as application level validators. When a record with check validators is exported additional CHECK constraints are being added to CREATE TABLE statement.

Doctrine provides the following simple check operators:

* '''gt'''
> greater than constraint ( > )
* '''lt'''
> less than constraint ( < )
* '''gte'''
> greater than or equal to constraint ( >= )
lsmith's avatar
lsmith committed
11
* '''lte'''
hansbrix's avatar
hansbrix committed
12 13 14 15 16 17 18 19 20 21
> less than or equal to constraint ( <= )


Consider the following example:

<code type='php'>
class Product extends Doctrine_Record
{
    public function setTableDefinition()
    {
lsmith's avatar
lsmith committed
22 23
        $this->hasColumn('id', 'integer', 4, 'primary');
        $this->hasColumn('price', 'decimal', 18, array('gt' => 0);
hansbrix's avatar
hansbrix committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
    }
}
</code>

When exported the given class definition would execute the following statement (in pgsql):

CREATE TABLE product (
    id INTEGER,
    price NUMERIC CHECK (price > 0)
    PRIMARY KEY(id))

So Doctrine optionally ensures even at the database level that the price of any product cannot be below zero.

> NOTE: some databases don't support CHECK constraints. When this is the case Doctrine simple skips the creation of check constraints.

If the Doctrine validators are turned on the given definition would also ensure that when a record is being saved its price is always greater than zero.

If some of the prices of the saved products within a transaction is below zero, Doctrine throws Doctrine_Validator_Exception and automatically rolls back the transaction.