当列名重复执行关系查询时,如何引用model's字段


Yii: How to refer to model's field when columns name duplication performing relational query?

我尝试在Yii中执行这个关系查询:

$r = MachineData::model()->with('machineGames')->findByPk($machine_id);

但是它返回这个错误:

CDbCommand failed to execute the SQL statement: SQLSTATE[42702]: Ambiguous column: 7         ERROR: column reference "machine_id" is ambiguous
LINE 1: ..."."game_id") WHERE ("t"."machine_id"=3) ORDER BY machine_id...

似乎问题是在ORDER BY条款中,对machine_id的引用是不清楚的。它可以指两个表,因为它们都有machine_id列。你能给我建议一个解决办法吗?的问候!

注。使用下面的CDbCriteria会产生相同的错误:

$criteria=new CDbCriteria();
$criteria->alias = "u";
$criteria->compare('u.machine_id',$machine_id);
$criteria->with = array('machineGames');
$r = MachineData::model()->findAll($criteria);

这是模型MachineData中的关系:

abstract class BaseMachineData extends GxActiveRecord {
  public function relations() {
    return array('machineGames' => array(self::HAS_MANY, 'MachineGames', 'machine_id', 'order'=>'machine_id', 'with'=>'game');
    }
  //code goes here
}
class MachineData extends BaseMachineData{
   //code goes here
}

这是模型MachineGames中的关系:

abstract class BaseMachineGames extends GxActiveRecord {
  public function relations() {
    return array('machine' => array(self::BELONGS_TO, 'MachineData', 'machine_id');
  }
  //code goes here
}
class MachineGames extends BaseMachineGames
{
  //code goes here
}

我认为问题在于你的MachineData::relations()方法:

public function relations() {
    return array('machineGames' => array(self::HAS_MANY, 'MachineGames', 'machine_id', 'order'=>'machine_id', 'with'=>'game');
    }

你应该消除*machine_id*的歧义,在CActiveRecord的文档中解释::relations():

public function relations() {
    return array('machineGames' => array(self::HAS_MANY, 'MachineGames', 'machine_id', 'order'=>'machineGames.machine_id', 'with'=>'game');
    }

NB:上面的代码使用了关系的名称,因此*machine_games。machine_id *列。如果您想消除主表列上的歧义(这里:*machine_data.machine_id*),请使用别名't'。