使用CActiveDataProvider进行简单查询 - Yii Framework

时间:2014-03-12 06:39:55

标签: php yii

如何在“CActiveDataProvider”中构建此查询:

$var = word;

    SELECT table_a.name, table_b.name
    FROM table_a
    LEFT JOIN table_b ON table_a.id = table_b.bid
    WHERE table_a.name LIKE '%$var%'

到目前为止我有这个模型:

class Table_a extends CActiveRecord {

    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    public function tableName() {
        return Yii::app()->db->tablePrefix.'table_a';
    }
}

2 个答案:

答案 0 :(得分:0)

您应该使用CDbCrtieria对象 参考http://www.yiiframework.com/doc/api/1.1/CDbCriteria

在你的情况下,你的控制器中会是这样的

<?php 
// .... Wherever you need the dataProvider, usually the action in the controller

$criteria = new CDbCriteria();
$criteria->addSeachCondition('table_a.name',$var,true,"AND","LIKE");
$criteria->join = "LEFT OUTER JOIN table_b ON t.id = table_b.bid";
$dataProvider = new CActiveDataProvider('table_a',array(
    'criteria'=>$criteria
    ));

答案 1 :(得分:0)

我没有测试过代码,但是它必须工作:

$dataProv=new CActiveDataProvider('Table_a',array(
          'criteria'=>array(
              'select'=>"table_a.name, table_b.name",
              'condition'=>"table_a.name LIKE '%$var%'",
              'join'=>"LEFT JOIN table_b ON table_a.id = table_b.bid",
          )));