Lukas Lukac
Lukas Lukac

Reputation: 8346

symfony2 entity oneToMany and methods

Hi i had fully successfully setted my entity onetoMany and ManyToOne i generated setters and getters and in user entity it created this method:

user entity:

    /**
 * @ORM\OneToMany(targetEntity="TB\RequestsBundle\Entity\Requests", mappedBy="followeeuser")
 */
protected $followees;   

requests entity:

/**
 * @ORM\ManyToOne(targetEntity="TB\UserBundle\Entity\User", inversedBy="followees")
 * @ORM\JoinColumn(name="followee_id", referencedColumnName="id", nullable=false)
 */ 
protected $followeeuser;

And when i using my own custom queries it works good... but i cant figure out how to use this generated function from symfony:

    public function addFollowee(\TB\UserBundle\Entity\User $followee)
{
    $this->followees[] = $followee;
}  

I dont know what to pass there... i tried first get user object based on id of user from twig... worked good but the error occur:

$user->addFollowee($userRepository->find($target_user_id));

Found entity of type TB\UserBundle\Entity\User on association TB\UserBundle\Entity\User#followees, but expecting TB\RequestsBundle\Entity\Requests

Upvotes: 0

Views: 5535

Answers (1)

Gmajoulet
Gmajoulet

Reputation: 700

Maybe you should think about what you're trying to before coding it. Grab a pen and a sheet of paper. :)

Tell me if I'm wrong, but here is what I think you're trying to do :

One user can have many "followee". One "followee" can have one user.

So, a OneToMany relation is ok.

Here is how to write it, from the doc :

Requests.php (btw, you should use Request.php)

/**
 * @ORM\ManyToOne(targetEntity="User", inversedBy="requests")
 **/
private $user;

User.php

/**
 * @ORM\OneToMany(targetEntity="Requests", mappedBy="user", cascade={"all"})
 **/
private $requests;

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

Now you can check if you your relation is ok, and update your schema :

php app/console doctrine:schema:validate
php app/console doctrine:schema:update --force

About getters/setters :

Requests.php

public function getUser()
{
    return $this->user;
}

public function setUser(User $user) // Please add a Use statement on top of your document
{
    $this->user = $user;
    return $this;
}

User.php

public function addRequest(Requests $request)
{
    $this->requests->add($request);
    return $this;
}

public function removeRequest(Requests $request)
{
    $this->requests->removeElement($request);
    return $this;
}

// Get requests and set requests (you know how to write those ones)

Now, to set a user to a Request, use

$request->setUser($user);

And to add a Request to a user, use

$user->addRequest($request);

Upvotes: 3

Related Questions