Active Record relationship for sending a simple message feature

I have the following three tables

  • person (id, name)

  • send_receive(id, from, to, messageID) /* from, to are foreign key of person table; messageID is the foreign key of message table */

  • message (id, messageBody)

in the person AR

public function relations()


		return array(

                	'receivedLookup'=>array(self::HAS_MANY, 'sendReceive', 'to')



But when I run

$result = $personA->receivedLookup

, I got an array of sendReceive AR, since count($result) is 5. My ultimate goal is to get the message body that the person A received. If Yii AR relationship is capable of doing this, how should I define the relationship? and How should I run the AR relationship query?

I’ve read the Guide several times, but still couldn’t figure out. Please help!

Thank you!

Your table structure and the way you have your relationship correctly states that you have a 1-to-many relationship between person and send_receive so of course you could have 0, 1, 5 or many more messages related to each person. If you then call person->receiveLookup, you will get all of these messages. If you only want one of the messages (or the latest message) you would have to process the array in the view and select which one(s) you wanted.

Thanks Lukos! This problem is solved!