[Solved] Default Scope With Relation Problem


1. Agent model

I have an Agent model, which has a default scope implemented like


where join is a session variable.

Note: I have disambiguated the agent_id, because other tables do also have this column. Otherwise exceptions occur on relational queries.

2. AgentRequest model

This is another model to store agent requests, it has following relationship with Agent

'agent' => array(self::BELONGS_TO, 'Agent', 'agent_id'),


Following exception occurs when trying to access the ‘agent’ relation. For example i am trying to access $model->agent in AgentReqest view _form.php.

CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘t.agent_id’ in ‘where clause’. The SQL statement executed was: SELECT agent.agent_id AS t1_c0, agent.first_name AS t1_c1, agent.last_name AS t1_c2 …(and other fields)

FROM mts_agent agent

WHERE (t.agent_id=4 or parent_id=4) AND (agent.agent_id=:ypl0). Bound with :ypl0=NULL

If i change

'agent' => array(self::BELONGS_TO, 'Agent', 'agent_id'),


'agent' => array(self::BELONGS_TO, 'AgentScopeLess', 'agent_id'),

Where AgentScopeLess is Agent model without default scope.

Then it is working fine, but i want to make it functional with default scope, as it has some sense as per my logic.

Waiting for your reply please.


Dear Friend

Let us declare the relationship in the following way.

'agent' => array(self::BELONGS_TO, 'Agent', 'agent_id','alias'=>'t'),


Solved, thanx.