sonam
sonam

Reputation: 3760

getting custom fields in doctrine 2

I have an entity as follow:

private $username;
private $password;
private $createdAt; //datetime

I want to run the query in doctrine to get the entities with the existing fields plus another field (in this case a column showing difference of createdAt and current datetime in minutes. In sql I would run query like:

 select username, password, createdAt,TIMESTAMPDIFF(MINUTE , created_at, NOW()) AS minutes from users

In doctrine I fetched the entity as below:

 $user = $em->getRepository('TestBundle:Users');

How can I get the custom field minutes from doctrine?

Upvotes: 4

Views: 4957

Answers (2)

Mirage
Mirage

Reputation: 31568

You can set up the function inside your Entity like

function GetDifference() {
     return getField1() - getField2()
}

Then that will be available for you every object

EDIT: Its very easy. Just like any other function

function getDateDifference() {
return abs(strtotime($createdAT) - strtotime($now));
}

Upvotes: 1

Venu
Venu

Reputation: 7289

You should check ResultSetMapping:

And check how to add scalar result

$rsm = new ResultSetMapping;
$rsm->addEntityResult('Users', 'u');
$rsm->addFieldResult('u', 'id', 'id');
$rsm->addFieldResult('u', 'password', 'password');
$rsm->addScalarResult('minutes', 'minutes');

$query = $this->_em->createNativeQuery('select username, password, TIMESTAMPDIFF(MINUTE , created_at, NOW()) AS minutes', $rsm);

$users = $query->getResult();

Upvotes: 6

Related Questions