Reputation: 1792
I try to execute this relational query in Yii:
$r = MachineData::model()->with('machineGames')->findByPk($machine_id);
but it returns this error:
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...
It seems the problem is in ORDER BY
clause where the reference to machine_id
is unclear. It may refer to both of the tables because they both have machine_id
column. Can you suggest me any solution, please?
REGARDS!
P.s. Using the following CDbCriteria gives the same error:
$criteria=new CDbCriteria();
$criteria->alias = "u";
$criteria->compare('u.machine_id',$machine_id);
$criteria->with = array('machineGames');
$r = MachineData::model()->findAll($criteria);
This is the relation in model 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
}
This is the relation in model 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
}
Upvotes: 0
Views: 1620
Reputation: 1207
I think the problem lies in your MachineData::relations() method:
public function relations() {
return array('machineGames' => array(self::HAS_MANY, 'MachineGames', 'machine_id', 'order'=>'machine_id', 'with'=>'game');
}
You should disambiguate *machine_id* here as explained in the docs for CActiveRecord::relations() :
public function relations() {
return array('machineGames' => array(self::HAS_MANY, 'MachineGames', 'machine_id', 'order'=>'machineGames.machine_id', 'with'=>'game');
}
NB : The code above is using the relation's name, hence the *machine_games.machine_id* column. If you want to disambiguate on the main table column (here : *machine_data.machine_id*), use the alias 't'.
Upvotes: 3