简体   繁体   English

检查是否在Yii中加载了关系

[英]Check if a relation is loaded in Yii

I'm trying to do something complex with a relation and avoid double loading: 我正在尝试使用关系执行复杂的操作并避免双重加载:

  • I have an object active record and each has a relation to some subject s through an objectSubject relation. 我有一个object活动记录,每个都通过objectSubject关系与某些subject有关系。

  • The type of the subject (in relation to the object ) is defined in the objectSubject with another relation. subject的类型(与object )在objectSubject定义了另一种关系。

  • Each object has zero or one subject relation of each type 每个object具有每种类型的零个或一个subject关系

I have the relations set up in the Object model as: 我将Object模型中的关系设置为:

'objectSubjects'=>array(self::HAS_MANY, 'ObjectSubject', 'object_id'),

And the ObjectSubject model as: ObjectSubject模型为:

'type'=>array(self::BELONGS_TO, 'Type', 'type_id'),
'subject'=>array(self::BELONGS_TO, 'Subject', 'subject_id'),

I would like to add a function to Object get the subject of an object by it's type .. 我想添加一个函数给Object通过它的type获取一个objectsubject

I can do: 我可以:

public function fetchSubject($key_string){
  $object_subject=$this->objectSubjects(array(
       'with'=>'subject'
       'scopes'=>array('typed'=>$key_string) /* Inner Join to type */
  ));
  return $object_subjects?$object_subjects[0]->subject:null;
}

But this will result in a DB query, even if the object_subject s with their type s and subject s are eagerly loaded into the object . 但是这将导致数据库查询,即使具有type s和subject s的object_subject被急切地加载到object

I would like to substitute the logic in the case that they are, and only query the one subject row if they are not.. is there any way to check if a relation has been loaded? 我想在它们是的情况下替换逻辑,并且只查询一个subject行,如果它们不是..有没有办法检查是否已加载关系?

Something like $this->isLoaded('objectSubjects') ? $this->isLoaded('objectSubjects')

Well what do you know? 好吧,你知道什么? There is a function 有一个功能

hasRelated(string $name)

that I totally missed in the AR docs . 我完全错过了AR文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM