Reputation: 103
I have a model for two tables message and User which contain fields:
Message: id message created_date status
User: id usr_name
I have another table message_to without a model:
message_to: id message_id user_id status
Now, My problem is I need to fetch username from usertable through user_id in message_to in the current message model. How can I create relation for this? I don't want to use query builder here.
Upvotes: 1
Views: 506
Reputation: 7295
In Message model:
<?php
class Message extends CActiveRecord {
// ...
public function relations() {
return array(
'user' => array(
self::BELONGS_TO,
'User',
'{{message_to}}(message_id, user_id)'
),
);
}
}
Then call like $message->user->usr_name;
To have an ability to get user's messages you can write a relation in User model:
<?php
class User extends CActiveRecord {
/...
public function relations() {
return array(
'messages' => array(
self::HAS_MANY,
'Message',
'{{message_to}}(user_id, message_id)'
),
);
}
}
Then call like foreach($user->messages as $message) { ...
Upvotes: 1