Model Relations Are Empty

For the update form i would like to pre select the categories and fill in the tags that belongs to the daytrip item.

I’ve created two get functions in the model that will store the selected categories and tags in public $categoryIds; and public $tagIds;.

Unfortunately, the debug print_r in the functions getDaytripCategories and getDaytripTags are empty ‘array( )’.

When i check the application log i see that ther is some lazy loading going on for categories and tags.


	public function actionUpdate()







	 * @return array relational rules.


	public function relations()


		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'city' => array(self::BELONGS_TO, 'City', 'city_id'),

			'categories' => array(self::MANY_MANY, 'Category', 'daytrip_category(daytrip_id, category_id)'),

			'tags' => array(self::MANY_MANY, 'Tag', 'daytrip_tag(daytrip_id, tag_id)'),




	* Getters for this model


	public function getDaytripCategories()


	print_r($this->categories); //DEBUG PRINT


		foreach ($this->categories as $n => $category)

			$data[] = $category->id_category;


		$this->categoryIds = $data;




	public function getDaytripTags()


	print_r($this->tags); //DEBUG PRINT


		foreach ($this->tags as $n => $tag)

			$data[] = array('id'=>$tag->id_tag, 'text'=>$tag->tag);


		$this->tagIds = CJSON::encode($data);




You are calling methods that should find relation in DB but they don’t have information how to find it. Why? Because you call them on statically created Daytrip::model() which returns instance without its representation in DB. So it have no ID, and relations don’t know how to find their related items.

I’m not quite understanding what you mean. Can you give an exemple how to fix this?


You are calling getDaytripCategories method on model, that is not retrieved from DB by for example model->findByPK or controller->loadModel, but on model created by modelName::model() which is returning global instance of this model and instance that is not saved in database. So it have no ID and in consequence have no relation with any items in db like categories or tags in your case.

You provided small context of your code but I guess that this line


is loading Daytrip model. Isn’t it?

If yest then fix is easy, jus replace the next 2 lines with it:



aah yeah, stupid :unsure:

Thank you!