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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度