Doctrine ORM


Doctrine 1.2 delete object and all relationships

Doctrine provides the ability to easily delete a doctrine record object and all it’s relationships. If you populate the entire doctrine object when it’s instantiated, just call the delete() method and it will delete everything. If you use lazy loading, you’ll need to call the delete method on each relationship –

$objRecord = Doctrine_Core::getTable('Table')->find(1);
$objRecord->RelationshipOne->delete();
$objRecord->RelationshipTwo->delete();
$objRecord->delete();

Doctrine 1.2 deep copy object and all relationships

Doctrine provides the ability to easily copy a doctrine record object and all it’s relationships. If you populate the entire doctrine object when it’s instantiated, just call the copy() method and pass a boolean “true” to the method so it will perform a deep copy. If you use lazy loading, you’ll need to load each relationship you want to copy with a line of code as below –

$objRecord = Doctrine_Core::getTable('Table')->find(1);
$objRecord->RelationshipOne;
$objRecord->RelationshipTwo;
$objRecord2 = $objRecord->copy( true );
$objRecord2->save();

Doctrine 1.2 on duplicate key update

Doctrine 1.2 doesn’t provide a way to do “on duplicate key update” query unless you do raw sql. However, they do provide a “replace” method that will get the job done. Your table will need a unique key or unique index on multiple columns for this to work, just like on duplicate key update. The different is that replace will delete the existing record and then insert a new one if the key is already found, so this might cause trouble if the table has an auto increment key.

Here is an example on how to use doctrine’s replace method

$obj = new Obj();
$obj->content_uuid = $content_uuid;
$obj->file_id = $fileId;
$obj->sort_order = $sortOrder;
$obj->replace();

How to select distinct with Doctrine_Query 1

There is a bug with doctrine and many tickets have been opened for it from what I saw. Doing the following in a query will return no result

$q = Doctrine_Query::create()
	->select('distinct(datetime_scraped)')
	->from('Rate')
	->orderBy('datetime_scraped desc');

The solution is to alias the distinct column like below

$q = Doctrine_Query::create()
	->select('distinct(datetime_scraped) as datetime_scraped')
	->from('Rate')
	->orderBy('datetime_scraped desc');

How To Truncate A Table With Doctrine 1

Doctrine ORM does not provide a built in method to truncate a table, so we must run a sql query manually. Use the below code and alter the SQL as needed:

$doctrine = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh();
$doctrine->query('TRUNCATE TABLE tableName');
unset($doctrine);