simPod
simPod

Reputation: 13466

Joining tables in Symfony Doctrine and accessing all the variables from Twig template

I'm new to Symfony and Doctrine and I'm trying to join two tables so I can then access the associated values from Twig template easily.

Here is my db scheme:

+--------------------------------------+--------------------+
|Messages                              |   User             |
|id    user        text        user_id |   id    name       |
|1     testuser    something   1       |   1     John       |
+--------------------------------------+--------------------+

This is my Message entity:

/**
 * @ORM\Entity
 * @ORM\Table(name="Messages")
 */
class Message {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    protected $user_id;

    /**
     * @ORM\Column(name="text", type="text")
     */
    protected $text;

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

And this is my User entity:

/**
 * @ORM\Entity
 * @ORM\Table(name="Users")
 */
class User {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

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

Then in controller I send $messages variable to Twig template:

$messages = $this->getDoctrine()->getEntityManager()->getRepository('MeMyBundle:Message')->findAll()

And the question is: Is the joing made properly? How can I access name property through message in Twig? Thanks.

Upvotes: 1

Views: 3528

Answers (1)

Scotty Waggoner
Scotty Waggoner

Reputation: 3380

Because of your many to one relationship, the variable $user in the Message class should be an object of type User. Because your variables $user and $name are private or protected, you should make getters and setter for them or make Doctrine generate them for you. After that $messages[i]->getUser()-getName() should work. (Generating getters and setters)

For more info about accessing attributes in relationships, take a deeper look at Fetching Related Objects section of the documentation.

From the same symfony documentation page "Of course, if you know up front that you'll need to access both objects, you can avoid the second query by issuing a join in the original query." If you want a true JOIN instead of a lazily loaded query you can write your own sql query following the documentation.

Upvotes: 2

Related Questions