dongtaogu8510 2012-04-25 13:24
浏览 72
已采纳

使用CDBCriteria执行连接查询

I am trying to do a Join query using CDBCriteria in Yii framework. The issue is the join query works successfully but it does not display the columns from other tables.

I am doing in the following way

$criteria = new CDbCriteria;

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

$criteria->select = '*';

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

When i run this, I can see only the mail table1 columns displayed. Other columns are not shown.

In my model class, I have the relation has

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

here command_id is common in table1 and table2.

This is how I am using the criteria code.

  • 写回答

1条回答 默认 最新

  • dongqin5604 2012-04-26 05:37
    关注

    As I said, Yii's Active Record implementation will only use columns which are defined in the table itself or the tables you are linking to through with, not arbitrary columns you return in the resultset.

    Solution 1: Define a relation to table2, add that relation to with, and get rid of join. Then you'll probably need to convert each returned object to an array - CJSON::encode will not handle a model with relations well.

    Solution 2: Use Yii::app()->db->createCommand("SQL query")->queryAll(); instead of Active Record. This will produce an array of arrays, which CJSON::encode will have no problem with.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大