Asmoria
Asmoria

Reputation: 9

Symfony 2 OneToMany

Fatal Error: Call to undefined method Doctrine\ORM\PersistentCollection::getPath()

User entity: User.php

namespace AppBundle\Entity;

 use Doctrine\ORM\Mapping as ORM;
 use Symfony\Component\Validator\Constraints as Assert;
 use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
 use Symfony\Component\Security\Core\User\UserInterface;
 use Doctrine\Common\Collections\ArrayCollection;

 /**
  * @ORM\Entity
  * @ORM\Table(name="users")
  */
 class User implements UserInterface, \Serializable
{

/**
 * @ORM\OneToMany(targetEntity="Avatars", mappedBy="user")
 */
protected $avatars;

/**
 * @return mixed
 */
public function getAvatar()
{
    return $this->avatars;
}


public function __construct()
{
    $this->avatars = new ArrayCollection();
}

/**
 * Get avatars
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getAvatars()
{
    return $this->avatars;
}

And Avatar Entity: Avatar.php

namespace AppBundle\Entity;

     use Doctrine\ORM\Mapping as ORM;
     use Symfony\Component\Validator\Constraints as Assert;
     use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

     /**
       * @ORM\Entity
       * @ORM\Table(name="avatars")
       */
     class Avatars
     {
/**
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="User", inversedBy="avatars")
 * @ORM\JoinColumn(name="user", referencedColumnName="id")
 */
private $user;


/**
 * @ORM\Column(type="string", length=54)
 */
private $path;

/**
 * @return mixed
 */
public function getPath()
{
    return $this->path;
}

Cannot reach Avatar Entity from controller:

HomeController.php

public function homeAction()
    {
        $usr= $this->get('security.token_storage')->getToken()->getUser();
        var_dump($user->getAvatar()->getPath());exit;
    }

Where I did mistake? Im only start to learn symfony framework, maybe i forgot to add any thing?

Upvotes: 1

Views: 99

Answers (1)

xabbuh
xabbuh

Reputation: 5881

You User entity contains a collection of Avatar objects and not just a single object. What you can do, for example, is to iterate the avatars and call getPath() on each single object like this:

foreach ($user->getAvatar() as $avatar) {
    var_dump($avatar->getPath();
}

By the way, the method name getAvatar() in your code in the User class is misleading as one will expect the user to have exactly one avatar and not a collection of avatars. I would rename it to getAvatars().

Upvotes: 3

Related Questions