Default Scope In Relational Query

I have following relations in the ‘User’ model:




  public function relations() {

    return array(

      'contact' => array(self::BELONGS_TO, 'Contact', 'contact_id'),

      'tasks' => array(self::MANY_MANY, 'UserTask', '{{user_tasks}}(user_id, user_task_id)', 'order'=>'tasks.name')

    );

  }



and the following default scope in the ‘Contact’ model:




  public function defaultScope() {

    return array('order'=>'name');

  }



If I try to query the ‘User’ model like this:




  $users = User::model()->with('tasks',	'contact')->findAll();



The order clause of the ‘Contact’ default scope is inserted into the query without table specification (‘ORDER BY tasks.name, name’), so the sql error “Integrity constraint violation: 1052 Column ‘name’ in order clause is ambiguous” is raised.

use

$users = User::model()->resetScope()->with(‘tasks’, ‘contact’)->findAll();

resetscope will not consider default scope & will work.

As I understand, you need to add to method Contact::defaultScope() return an alias for you model, like:




  public function defaultScope() {

    return array('alias' => 'contact', 'order'=>'contact.name');

  }



to take off ambiguous fields name.

great! thanks for saving the day.