I have searched for a while now and the docs aren’t really clear to me and i couldn’t find any example either.
Using a simple relation on a class called World
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(
'players' => array(self::HAS_MANY, 'Player', 'worldid'),
'users'=>array(self::MANY_MANY, 'User',
'Player(userid, worldid)'),
);
}
then when i construct a model everything still works:
The good thing about defining relations is that the class records them and can generate the SQL to join tables itself using them Once you’ve defined a relation, all you need to do is to call it by name in your ‘with’ array.
Well, Together is not actually required. I included it as your working code seemed to.
It merely changes how the content is loaded, which could potentially improve performance. It’s not required, however, and might not be optimal depending on the query. Using ‘with’ isn’t strictly required either, it just tells Yii to load all of the related records in one go… If you try and access a related record that hasn’t been loaded, Yii will load it lazily, one record at a time.
Its not perfect, but unless your tables are massive, these optimisations are unlikely to matter. If your tables are massive then I’d suggest benchmarking before assuming that any given option should be used… Once memory limitations come into play servers can grind to a halt.
Also, is there a particular reason you used a many-many relationship for Users? Did you know you could define a relation in Player and load it using with?
users can join mutiple worlds and worlds can have multiple users so is MANY_MANY
but since each user can have different settings in each world and i needed to create a relation table for the MANY_MANY relation anyway i made it Player
and i store those settings in Player aswell, saves me a table