我尝试在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
列。你能告诉我任何解决方案吗?
REGARDS!
P.S。 使用以下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
}
答案 0 :(得分:3)
我认为问题在于你的 MachineData :: relations()方法:
public function relations() {
return array('machineGames' => array(self::HAS_MANY, 'MachineGames', 'machine_id', 'order'=>'machine_id', 'with'=>'game');
}
您应该按照CActiveRecord::relations()的文档中的说明在此处消除歧义* machine_id *:
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”。