Yii - 使用关系中定义的范围的关系 [英] Yii - using relations with scopes defined in the relation
问题描述
我有一个模型,其中的一些关系定义如下.
I have a model with some relations 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 linking table and the linked items have a valid scope:
public function scopes() {
return array(
'valid'=>array(
'condition'=>"t.`valid`=1",
),
);
}
为了使生成的连接查询与关系范围一起工作,我不得不按如下方式修改范围:
In order for the generated join queries to work with the relation scope, I have had to modify the scopes as follows:
public function scopes() {
return array(
'valid'=>array(
'condition'=>"`linkingTable`.`valid`=1",
),
);
}
和:
public function scopes() {
return array(
'valid'=>array(
'condition'=>"`linkedItems`.`valid`=1",
),
);
}
问题是这些范围在直接从链接模型中使用时将不起作用,即:
The problem is that those scopes will not work when used from the linked model directly, i.e.:
$linkedItems = LinkedItem::model()->valid()->findAll();
导致错误说 linkedItems
不是定义的别名.当然,这是可以理解的.它还导致任何其他想要拥有一些 LinkedItems 的模型都需要以完全相同的方式定义关系.
Results in an error to say that linkedItems
isn't a defined alias. Which is understandable, of course. It also results in a need for any other model who wants to own some LinkedItems needing to define the relation in the exact same way.
是为每个用例定义不同范围的唯一解决方案,如下所示:
Is the only solution to define a different scope for each use case, like this:
public function scopes() {
return array(
'valid'=>array(
'condition'=>"t.`valid`=1",
),
'validForModelRelation'=>array(
'condition'=>"`linkedItems`.`valid`=1",
)
);
}
这感觉有点笨拙.我想知道是否有更好的方法来做到这一点?
This feels a bit cludgey. I am wondering if there is a better way of doing this?
推荐答案
您需要能够获取表的当前别名.t
单独时,或关联模型时的关系名称.在相关模型的范围内,您可以使用:
You need to be able to get the current alias of the table. t
when it's alone, or the relation name when it's a related model. In the scope of the related model you can use:
public function scopes() {
return array(
'valid'=>array(
'condition'=>$this->tableAlias.".`valid`=1",
),
);
}
如果你在 defaultScope
中使用它,你需要使用 $this->getTableAlias(false, false).
作为防止无限循环的参数,试图找到别名.
If you use it in the defaultScope
however, you need to use $this->getTableAlias(false, false).
as the parameters to prevent an infinite loop, trying to find the alias.
缺少点
这篇关于Yii - 使用关系中定义的范围的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!