Yii - use of relationships with areas defined in the relationship

I have a model with some relationships defined as follows.

public function relations() { return array( 'linkingTable' => array(self::HAS_MANY, 'LinkingTable', array('this_id'=>'id'), 'scopes'=>array('valid')), 'linkedItems' => array(self::HAS_MANY, 'LinkedItem', array('linked_item_id'=>'id'), 'through'=>'linkingTable', 'scopes'=>array('valid')), ); } 

Both the link table and related elements have a valid scope:

 public function scopes() { return array( 'valid'=>array( 'condition'=>"t.`valid`=1", ), ); } 

In order for the generated join requests to work with the scope of relations, I had to change the scope of operations as follows:

 public function scopes() { return array( 'valid'=>array( 'condition'=>"`linkingTable`.`valid`=1", ), ); } 

and

 public function scopes() { return array( 'valid'=>array( 'condition'=>"`linkedItems`.`valid`=1", ), ); } 

The problem is that these areas will not work when used directly from a related model, that is:

 $linkedItems = LinkedItem::model()->valid()->findAll(); 

The results are in error to say that linkedItems not a specific alias. This is understandable, of course. It also leads to the need for any other model that wants to own some LinkedItems that need to accurately define relationships in the same way.

This is the only solution to define a different scope for each use case, for example:

 public function scopes() { return array( 'valid'=>array( 'condition'=>"t.`valid`=1", ), 'validForModelRelation'=>array( 'condition'=>"`linkedItems`.`valid`=1", ) ); } 

It feels a bit cludgey. I am wondering if there is a better way to do this?

+4
source share
2 answers

You should be able to get the current table alias. t when it is one, or the name of a relationship when it refers to the corresponding model. Within the framework of the corresponding model, you can use:

 public function scopes() { return array( 'valid'=>array( 'condition'=>$this->tableAlias.".`valid`=1", ), ); } 

However, if you use it in defaultScope , you need to use $this->getTableAlias(false, false). as parameters to prevent an infinite loop, trying to find an alias.

edit: point missing

+6
source

You need a DOT before 'Condition' => $ this-> tableAlias. " valid = 1",

0
source

Source: https://habr.com/ru/post/1432904/


All Articles