duanjiaopi8218 2013-09-20 06:40
浏览 78
已采纳

Yii PHP:数据库 - 根据偏好获取列条目的正确方法

say with a structure like this., columns are :

first_name | second_name | middle_name | last_name

Now, suppose i have a form that requires to enter a "name"..but not specifying what type of name it is.

And on the controller, i have to check whether that "name" is in the database.

I do it like this:

public function actionCheckName($name){

$name = PersonName::model()->findByAttributes(array('first_name'=> $name));
//then check if the name exists in the first_name column

if(!empty($name)){
$name = PersonName::model()->findByAttributes(array('second_name'=> $name));
}
//if it's not in the first_name column...check in the second_name column

..
..and so on, i hope you get the idea

}

i basically don't know whether what type of name did the user enter... but i have to check in the database if the entry exists..whether in one of these name types.

the code above works.but looks..a little...not-so-good.. Is there a better way to do this? Many Thanks!

  • 写回答

2条回答 默认 最新

  • dsb53973 2013-09-20 06:50
    关注
            $criteria=new CDbCriteria;
            $criteria->compare('first_name', $name, false, 'OR'); // The 3th param determine if the string comparation use "LIKE" or "="
            $criteria->compare('second_name', $name, false, 'OR');
            $criteria->compare('middle_name', $name, false, 'OR');
            $criteria->compare('last_name', $name, false, 'OR');
    
            $nameList = PersonName::model()->findAll($criteria); // Return all PersonName with $name in any field.
    
            $name = PersonName::model()->find($criteria); // Return the first PersonName with $name in any field.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题