Claire
Claire

Reputation: 3773

Getting a foreign key field other than id in symfony

I have a table 'comment', investigation that has a field referencing another table 'sf_guard_user'. At the moment when I put

<?php echo $investigationComment->getUserId() ?>

I get the id value of the foreign table row. I want to be able to get the name field value.

Somewhere else in my project I was able to omit id from getUserId() and then put->getName() and it brought me that field value, but for this it's not doing it for some reason. How can I get the name value for the foreign key row?

Upvotes: 0

Views: 1774

Answers (2)

PrestonDocks
PrestonDocks

Reputation: 5408

The easiest way to do this is to add the following your foreign entity class

public function __toString(){
    return $this->getAPropertyOnYourEntity();
}

Now rather than returning the ID the entity can return any property you want from the __toString() function.

Upvotes: 0

Dziamid
Dziamid

Reputation: 11571

Just get the relation object first and then call for any property of that relation.

<?php echo $comment->getUser()->getName() ?>

This will work if you defined an alias 'User' in your relation like this:

//config.yml
Comment:
  relations:
    sfGuardUser:
      alias: User
      foreignAlias: Comments
      local: user_id
      foreign: id

or

//config.yml
Comment:
  relations:
    User:
      class: sfGuardUser
      foreignAlias: Comments
      local: user_id
      foreign: id

Upvotes: 5

Related Questions