2

我正在尝试在 Yii 框架中使用 CDBCriteria 进行 Join 查询。问题是连接查询成功运行,但它不显示其他表中的列。

我正在按照以下方式进行

$criteria = new CDbCriteria;

$criteria->order = 't.id desc';

$criteria->select = '*';

$criteria->join = ' INNER JOIN table2 INNER JOIN table3 INNER JOIN table4';

当我运行它时,我只能看到显示的邮件 table1 列。其他列未显示。

在我的模型类中,我的关系有

public function relations()
{
  // NOTE: you may need to adjust the relation name and the related
  // class name for the relations automatically generated below.
    return array(
      'user' => array(self::BELONGS_TO, 'DmPhoneUser', 'user_id'),
      'command' => array(self::BELONGS_TO, 'DmOtaCommand', 'command_id'),
      'partner' => array(self::BELONGS_TO, 'DmPartner', 'partner_id'),
    );
}

** * ** * ** * ** * ** * ** * ** * ** * ** * ** * ** * ** * ** * ** * ** * ** * ** * ** * **

public function actionGetHistory($start, $per_page)
{
    $partner_id = '10';
    $criteria = new CDbCriteria;
    $criteria->order = 't.history_id desc';
    $criteria->select = 't.*, table2.*';
    $criteria->join = ' INNER JOIN table2 ON t.command_id = table2.command_id';
    $result = Table_1_class::model()->with('command')->findAll();
    $history_data = CJSON::encode($result);
    echo $history_data;
}

这里command_id在table1和table2中很常见。

这就是我使用标准代码的方式。

4

1 回答 1

4

正如我所说,Yii 的 Active Record 实现将只使用在表本身或您通过链接到的表中定义的列with,而不是您在结果集中返回的任意列。

解决方案 1:定义与 的关系table2,将该关系添加到with,然后删除join。然后您可能需要将每个返回的对象转换为一个数组 -CJSON::encode不能很好地处理具有关系的模型。

解决方案 2:使用Yii::app()->db->createCommand("SQL query")->queryAll();而不是 Active Record。这将产生一个数组数组,这CJSON::encode将没有问题。

于 2012-04-26T05:37:57.247 回答