How to deal with foreign keys properly?

I have created two tables, entity and alt. Each entity can have many alts but each alt belongs to only one entity.

This done with an InnoDB, with foreign keys. When I model this with yiic, this seems to be reflected.




	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(

			'alts' => array(self::HAS_MANY, 'alt', 'entity_id'),

			'contents' => array(self::MANY_MANY, 'content', 'entity_content(content_id, entity_id)'),

			'tags' => array(self::MANY_MANY, 'tag', 'entity_tag(tag_id, entity_id)'),

			'events' => array(self::HAS_MANY, 'event', 'entity_id'),

			'relations' => array(self::HAS_MANY, 'relation', 'child_id'),

		);

	}




for models/entity.php

and


	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(

			'entity' => array(self::BELONGS_TO, 'entity', 'entity_id'),

		);

	}

for models/alt.php

I have myself lowered the case on the 2nd paramaters in the array, thinking it might be a case issue, as the table names are lowercase. Neither however seems to work as I thought it would.

I have then made crud for both, and would expect, especially when working with the alt crud pages to see data being loaded, so that I can select an entity from a dropdown in the alt update. I have used firephp to dump the entire data being loaded, but while there is a mention of the foreign key, there is no attempt to load any data from the related table.

UPDATE: The data is loaded from the database, a proper query is generated with a join and in the command line this gives the correct result, a joined table. I did add a ->with(‘entity’) to the model definition

However, it still remains unclear how to then use this? If I dump the model, I see only the base attributes listed, none of the data of the joined table seems to be there.

There is probably a step missing, but while I have found a number of ways to add foreign key constraints, I seem to have looked over the method of making the default crud pages to use it?

What am I missing? I tried searching for it, but I don’t know the proper terms for this. Foreign key results all seem to discuss missing relations function, but that seems to be generated just fine.

What is the correct way to display a value from a foreign table in a standard crud page as generated by YIIC?

Anyone can point me in the direction of an example?

You need to write code to pull data from a related model, crud does not do that for you.