简体   繁体   中英

Left Join with Yii CDbCriteria

I have a query as follows:

SELECT messages.id, 
       messages.sender_id, 
       messages.subject, 
       messages.body, 
       messages.created_at, 
       user.username AS username  
FROM messages  LEFT JOIN user ON user.iduser=messages.sender_id

I tried to change the query to the CDbCriteria model's as follows:

$criteria   = new CDbCriteria();
$criteria->select = "messages.id, messages.sender_id, messages.subject, messages.body, messages.created_at, user.username AS username";
$criteria->alias  = "messages";
$criteria->join   = "LEFT JOIN user ON user.iduser=messages.sender_id";
$messagesAdapter = Message::model()->findAll($criteria);

But, when I execute the query, appear error as follows:

Property "Message.username" is not defined.

What is an error in the query ? Please help.

You should use relation name to print the username or user attributes , ie. user.*.

For that you should have relation in you Message model for User model. Something like..

public function relations()
{
    return array(            
        ......
        ......

        'userRel' => array(self::HAS_MANY, 'User', 'isuser'),
        ......
    );
}

Now, you can print username using this relation name userRel

//check this
print_r($messagesAdapter[0]->userRel);

//May be you can get username with below statement as you are using left join
echo $messagesAdapter[0]->userRel[0]->username;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM