Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a relation is loaded in Yii

Tags:

php

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 subjects through an objectSubject relation.

  • The type of the subject (in relation to the object) is defined in the objectSubject with another relation.

  • Each object has zero or one subject relation of each type

I have the relations set up in the Object model as:

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

And the ObjectSubject model as:

'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..

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_subjects with their types and subjects are eagerly loaded into the 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?

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

like image 979
Arth Avatar asked Oct 01 '22 01:10

Arth


1 Answers

Well what do you know? There is a function

hasRelated(string $name)

that I totally missed in the AR docs.

like image 197
Arth Avatar answered Oct 03 '22 02:10

Arth