繁体   English   中英

使用CDBCriteria进行联接查询

[英]Doing Join query using CDBCriteria

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

我正在按照以下方式做

$criteria = new CDbCriteria;

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

$criteria->select = '*';

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

运行此命令时,我只能看到显示的mail 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在表1和表2中很常见。

这就是我使用条件代码的方式。

就像我说的那样,Yii的Active Record实现将仅使用表本身或通过with链接到的表中定义的列,而不使用您在结果集中返回的任意列。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM