symfonycontrollermany-to-manycreatequery

Symfony2, get elements from manytomany relation in controller


I have an entity "Clients" with a relation manytomany with an entity "Preferences", so there is an intermediate table clients_preferences of course.

The relation works FINE and for a client I can display all its preferences in TWIG with something like

{% if not client.preferences.empty %}
   <p>
     {% for preference in client.preferences %}
          {{ preference.name }}{% if not loop.last %}, {% endif %}
     {% endfor %}
   </p>
 {% endif %}

BUT:

I want to be able to get the preferences list INSIDE my controller Something like

$preferences = $preference1." - ".$preference2......;

(It is because I will need to send this list after via JSON...)

So, I create a query to get my client row:

$query = $em->createQuery('SELECT c FROM SamplemyBundle:Clients c WHERE c.email = ?1')
->setParameter(1, $email);

$result = $query->getSingleResult();

As you see I select one client by his email, and I get one row in return because the email is unique and I am able to have different things from the client like his firstname, lastname etc...by doing:

$firstname = $result->getFirstname();

All is fine, just the problem is that I don't know how to deal with the preferences list in the controller. I guess I have to make a loop....

Below my entity Clients

class Clients
{
  /**
   * @ORM\ManyToMany(targetEntity="Sample\myBundle\Entity\Preferences", cascade={"persist"})
   */
   private $preferences;

  /**
   * @var integer
   *
   * @ORM\Column(name="id", type="integer")
   * @ORM\Id
   * @ORM\GeneratedValue(strategy="AUTO")
   */
   private $id;

  /**
   * @var string
   *
   * @ORM\Column(name="firstname", type="string", length=255)
   */
   private $firstname;

And my entity Preferences

class Preferences
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

If someone has an idea, it will be great, thank you by advance.


Solution

  • The preferences will be set to a Doctrine\Common\Collections\ArrayCollection containing instances of Preferences. So you can just loop over them as if they were an array.

    $preferences = array();
    foreach ($result->getPreferences() as $preference) {
        $preferences[] = $preference->getName();
    }
    $preferenceString = implode(' - ',$preferences);
    

    Edit: typo