Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if an object from a relation exists in the database

I'm using Symfony with Doctrine.

I have two classes defined, Person and Student, a relation one to one.

Each Student is related to a Person, but not every Person has a relation with a Student.

When I call ...

$person->getStudent();

... I always get and object, regardless some Person's doesn't have a Student. How can I know it doesn't (the Student) exist in the database?

Thanks.

like image 480
kiewic Avatar asked Jan 20 '10 00:01

kiewic


3 Answers

I think

$person->getStudent()->exists();

should do it. At least according to the Doctrine API documentation.
The object you get is probably some kind of Null record.

like image 174
Felix Kling Avatar answered Oct 23 '22 18:10

Felix Kling


You can also use Doctrine_Record::relatedExists(), which is kind of a complement to hasReference()

You use it like this:

if ($person->relatedExists('Student'))
like image 35
John Carter Avatar answered Oct 23 '22 20:10

John Carter


There's a pretty new method (I think since Doctrine 1.2): $person->hasReference("Student"); returns a boolean for whether there is actually a Student associated to the person, no matter whether it was saved already or not in database, and as desired without creating a new Student record. This call can be suitable in situations when application logic doesn't care about the persistence of the related object, e.g. while within a transaction (I guess). Hope that helps a bit, cheers, RAPHAEL

like image 2
Raphael Schumacher Avatar answered Oct 23 '22 18:10

Raphael Schumacher