Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to get foreign table if there are two foreign key to same table?

This is the Model, and I want get both user's data


    class PersonalMessage extends BaseModel
    {

        public $fromUserId;
        public $toUserId;

        public function initialize()
        {
            $this->belongsTo('fromUserId', 'User', 'id', array('foreignKey' => true));
            $this->belongsTo('toUserId', 'User', 'id', array('foreignKey' => true));
        }
    }

and I use this to get user

    {{personalMessage.user.username}}

But I can only get the data which linked to toUserId

How can I get the other user?



20.3k
Accepted
answer
$this->belongsTo('fromUserId', 'User', 'id', array('alias' => 'fromUser'));
$this->belongsTo('toUserId', 'User', 'id', array('alias' => 'toUser'));