如何在CdBCriteria中使用LIKE撰写查询?

时间:2013-10-03 05:58:18

标签: activerecord yii

我已经阅读了一些帖子,文档。仍然不明白为什么这段代码不起作用。有人可以帮我解决这个问题吗?

class SearchController extends Controller
{
    public function actionResults()
    {
        $search = $this->getPost('search', '');

        $criteria = new CDbCriteria();

        $criteria->condition = 'username like :username';

        $criteria->params = array(
            ':username' => '"%' . $search . '%"'
        );

        $results = User::model()
            ->findAll($criteria);

        $this->render('search', array(
            'search' => $search,
            'results' => $results,
        ));
    }
} 

Yii Profiler总是向我显示此查询:

SELECT * FROM `user` `t` WHERE username like :username

我不明白为什么“:username”仍然是“:username”,不能用$ search值替代。


我已经用这个解决方案解决了:

class SearchController extends Controller
{
    public function actionResults()
    {
        $results = User::model()
            ->findAll(array(
                'condition' => 'username like :username',
                'params' => array(
                    ':username' => '%'. $this->getPost('search') .'%'
                )
            ));

        $this->render('search', array(
            'search' => $this->getPost('search'),
            'results' => $results,
        ));
    }
}

但仍然不明白为什么探查器会向我显示不完整的查询而不是渲染的查询。

2 个答案:

答案 0 :(得分:1)

你可以像这样使用addSearchCondition函数, 对于ref http://www.yiiframework.com/doc/api/1.1/CDbCriteria#addSearchCondition-detail

    $criteria = new CDbCriteria();
    $criteria->addSearchCondition('username',$search);

答案 1 :(得分:0)

class SearchController extends Controller
{
    public function actionResults()
    {
        $results = User::model()
            ->findAll(array(
                'condition' => 'username like :username',
                'params' => array(
                    ':username' => '%'. $this->getPost('search') .'%'
                )
            ));

        $this->render('search', array(
            'search' => $this->getPost('search'),
            'results' => $results,
        ));
    }
}