Yii Framework Forum: Active Record: Accessing Foreign Record Parameters - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Active Record: Accessing Foreign Record Parameters Rate Topic: -----

#1 User is offline   MrVein 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 17-February 13

Posted 17 February 2013 - 12:01 PM

Hi folks!

I'm trying and suffering for 3 hours now and I begin to doubt.
I've a model 'Message' with these relations:
public function relations() {
        return array(
            'user' => array(self::BELONGS_TO, 'User', 'user'),
        );
    }

and these properties: id, message, user

The relations of the user-model:
'messages' => array(self::HAS_MANY, 'Message', 'user'),

And these properties: id, name


The name of the user must appear in the view when I do a foreach on my messages.
So I tried this code:
echo $message->user->name;


but it fails... When i do $message-> user, I get the right id.

Now the question: Is this possible? Or do I have to write a function in the message-model in which a usermodel is loaded.

Thanks in advance!
0

#2 User is offline   haosmark 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 35
  • Joined: 27-January 13

Posted 17 February 2013 - 03:36 PM

Yeah that's pretty much how you do it as far as I know. Not sure why it isn't working for you.
Are your tables in InnoDB engine and foreign keys tied to name?
0

#3 User is offline   softark 

  • Keep It Simple
  • Yii
  • Group: Moderators
  • Posts: 2,063
  • Joined: 16-February 11
  • Location:Japan

Posted 17 February 2013 - 08:10 PM

Hi MrVein, welcome to the forum.

The cause of the problem is that you share the same name for an attribute and a relation.

Try this for testing:
public function relations() {
        return array(
            'm_user' => array(self::BELONGS_TO, 'User', 'user'),
        );
    }
...
echo $message->m_user->name;


It's better to use 'user_id' instead of 'user' for the name of the FK column.
Guidelines for good schema design > DO name your foreign key fields ending in "id"
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users