开发者

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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜