Active Record: Accessing Foreign Record Parameters

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!

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?

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"