简体   繁体   中英

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

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!

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

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'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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