0

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

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 探查器总是向我显示这个查询:

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,
        ));
    }
}

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

4

2 回答 2

1

您可以像这样使用 addSearchCondition 函数,参考http://www.yiiframework.com/doc/api/1.1/CDbCriteria#addSearchCondition-detail

    $criteria = new CDbCriteria();
    $criteria->addSearchCondition('username',$search);
于 2013-10-03T06:01:59.237 回答
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,
        ));
    }
}
于 2013-10-03T06:34:00.533 回答