Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii: How to set unique table alias for model

Tags:

php

yii

I'am working on two models.

  1. Credentials
  2. Messages

Credentials model has a default scope method, where I've added addNotInCondition to filter blocked users. Here is my code

public function defaultScope() {
  $criteria = new CDbCriteria();
  $criteria->addNotInCondition("t.id", BanUser::model()->bannedUsers);
  return $criteria;
}

This works fine. But While accessing credentials model from Messages model, it gives me error. Unknown column 't.id'. (BELONGS_TO relation is defined in messages model)

$message->credential; //this generate error.

What could be solution to this problem. I know this is due table aliases. I'm stuck here. Please help.

like image 456
Ejaz Karim Avatar asked Oct 20 '25 06:10

Ejaz Karim


2 Answers

You can set table alias for model by its default scope method:

/**
* @return array default scope (applies only to SELECT statements)
*/
public function defaultScope () {
    return array(
        'alias' => $this->tableName(),
    );
}

Then use alias elsewhere too, e.g. in search:

public function search () {
    $criteria = new CDbCriteria;
    $criteria->alias = $this->tableName();
    $criteria->compare( $criteria->alias.'.id', $this->id );
    return new CActiveDataProvider( $this, array(
        'criteria' => $criteria,
    ) );
}
like image 136
Maug Lee Avatar answered Oct 21 '25 21:10

Maug Lee


First of all, you can get current model alias name like this:

public function defaultScope() {
  $alias = $this->getTableAlias(false,false);

  $criteria = new CDbCriteria();

  $banned = array();

  foreach(BanUser::model()->bannedUsers as $user)
      $banned[] = $user->id;

  $criteria->addNotInCondition($alias.".id", $banned);
  return $criteria;
}

Then I'm not sure about BanUser::model()->bannedUsers. Manual tells us that addNotInCondition accepts array (i.e. ('val1','val2','val3','etc')). If I remember well, relational fields aren't arrays of values, but are objects.

like image 29
apoq Avatar answered Oct 21 '25 19:10

apoq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!