kiewic
kiewic

Reputation: 16420

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.

Upvotes: 6

Views: 1250

Answers (3)

John Carter
John Carter

Reputation: 55271

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

You use it like this:

if ($person->relatedExists('Student'))

Upvotes: 3

Raphael Schumacher
Raphael Schumacher

Reputation: 21

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

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816334

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.

Upvotes: 9

Related Questions