iamthestreets
iamthestreets

Reputation: 773

Symfony 3 - Using ManyToOne and OneToMany and retrieving the data

I have a User table and a Job Title table in my database.

I have setup a User entity and a JobTitle entity.

In my User entity I have:

 /**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\JobTitle", inversedBy="users")
 * @ORM\JoinColumn(name="job_title_id", referencedColumnName="id")
 */
public $jobTitle;

In my JobTitle entity I have:

/**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\User", mappedBy="jobTitle")
 */
private $users;

Here is an example setup in User Table:

job_title_id | Username
1            | jdoe 

Here is an example setup in job Title Table:

id | job_title
1  | Owner

When I create the user everything is entered into the database as expected.

My issue is displaying the actual job title in my users list page.

Here is my Controller:

/**
 * @Route("/users", name="users")
 */
public function listAction()
{
    $loggedInUser = $this->getUser();
    $users = $this->get('fos_user.user_manager')->findUsers();

    if (!is_object($user) || !$user instanceof UserInterface) {
        throw new AccessDeniedException('This user does not have access to this section.');
    }
    return $this->render('users/users.html.twig', array(
        'user' => $loggedInUser,
        'users' => $users,
    ));
}

In my twig template I was trying to use {{ user.jobTitle }}, but I get a conversion to string error which makes sense, but I have not idea how to get the actual job title name to display in the twig page.

If you need more info please let me know.

How do I retrieve the job title name using the job_title_id in the users table?

Upvotes: 0

Views: 39

Answers (1)

Alvin Bunk
Alvin Bunk

Reputation: 7764

You haven't shown all your entities, so I'll have to 'guess' based on what I see above.

Looks like this: {{ user.jobTitle }} returns you a JobTitle object. You can confirm by doing a dump.

Since it's an object, I suspect you'll need to do something like this:

{{ user.jobTitle.job_title }}

Or possibly use the JobTitle's object methods (don't know what they are):

{{ user.jobTitle.getJobTitle }}

Or something like that. Try it out.

Upvotes: 1

Related Questions