简体   繁体   中英

how to return model in function with Yii

I want to check if a user with the specified ID was created or not, if not I will create a new user and return it. And if the user already existed, I will return it. When I do this, the server can't load. I have 2 functions:

public function actionCreateNewUser() {
    $aID = "4324";
    $rs = $this->canCreateNewUser($aID);
}
public function canCreateNewUser($aID) {
    $rsUser = User::model()->find('AID=:aID', array('aID' => $aID));
    return $rsUser[0];
}

The canCreateNewUser implementation is wrong because find returns either a User model or null . It should be written like this instead:

public function canCreateNewUser($aID) {
    return User::model()->find('AID=:aID', array('aID' => $aID)) === null;
}

You can also extend User with a findOrCreate method that returns either an existing instance or creates a new one on the spot:

public function findOrCreate($aID) {
    $existing = User::model()->find('AID=:aID', array('aID' => $aID));
    if (!$existing) {
        User::model()->insert(array('aID' => $aID));
    }

    return $existing ?: User::model()->find('AID=:aID', array('aID' => $aID));
}

You can do like that to avoid returning invalid index for non object

$result = User::model()->find('AID=:aID', array('aID' => $aID));

return ($result)?$result[0]:NULL;

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