nowiko
nowiko

Reputation: 2557

I receive Persitent Collection instead of ArrayCollection

I want to see if my record in database has related photos or not. But when I call $car->getCarPhotos() , I get the instance of Doctrine\ORM\PersistentCollection, and var_dump show the same result for car what has photos, and for car what has no car_photos. Where is my problem? Please , help me.

Upvotes: 0

Views: 82

Answers (2)

qooplmao
qooplmao

Reputation: 17759

Should be a comment but it's terrible for code..

You could add one of a few methods to your model that would be able to tell you if you had any photos attached.

/**
 * Check if this car has any attached photos
 *
 * @return boolean
 */
public function hasPhotos()
{
    return false === $this->carPhotos()->isEmpty();
}

Which could be called as if ($car->hasPhotos())

/**
 * Count how many photos this car has.
 *
 * @return integer
 */
public function getNbCarPhotos()
{
    return $this->carPhotos()->count();
}

Which could be called as if ($car->getNbPhotos() > 0) or if ($car->getNbPhotos() !== 0)

Upvotes: 1

Igor Pantović
Igor Pantović

Reputation: 9246

So what is bothering you? It is supposed to return you collection in both cases. To check whether car has related photos:

if ($car->getCarPhotos()->isEmpty()) {
    // Car has no photos
} else {
    // Car has photos
}

Upvotes: 1

Related Questions