Relations types
Introduction
In abstractModels point of view, relationships between models are defined as hasOne or hasMany relationship.
hasOne
A hasOne relation is applied everywhere a model has one other model as a property. Regarding our sample database at modelGeneration#ExampleDatabase, this is the kind of relationship posts have with users, posts have one user Most of the time it corresponds to a field in database that points to another table that contains other models.
hasOne definition as models property
each extended abstractModel class has a static property named $hasOne that describe relation between the model and other models it own or belong to. let's explain how this work and how to change parameters defined by the modelGenerator to better sweet our needs.
<?php class posts extends BASE_POSTS{ static protected $hasOne = array( // 'relName'=> array('modelName'=>'modelName','relType'=>'ignored|dependOn|requireBy',['localField'=>'fldNameIfNotPrimaryKey','foreignField'=>'fldNameIfNotPrimaryKey','foreignDefault'=>'ForeignFieldValueOnDelete']) 'user' => array( 'modelName'=>'users', 'localField'=>'user', 'relType'=>'dependOn', ), ); }
so each hasOne relation is defined has an entry in this property. The key used in model::$hasOne property determine how we will access to the related model using a declared instance of this model: in other words in the previous sample this mean that we can access user of a post like this
$post = posts::getInstance($instanceId); $user = $post->user;
each hasOne entry is defined by parameters:
- modelName : the class name of the extended model related to the current model
- relType : one of ignored, dependOn or requireBy see further in this page for more explanation on this.
- localField : this is the name of the database field name in the table of current model that is the primaryKey of the related model.
- foreignField : this is the name of the database field name in the table of related model that is referenced in the local field, this only need to be set if it's not the related model primaryKey.
- foreignDefault: the default value of the foreign field. This is used at delete time to eventually set the foreignField to its default value instead of deleting it too (only used on ignored or dependOn relations).
hasMany
A hasMany relation is applied everywhere a model has many models as a single property (we will talk of modelCollection?). Typically when looking at modelGeneration#ExampleDatabase, this is the kind of relation users have with posts. a single user can have many posts that belong to him. Most of the time it is the complementary relation of a hasOne relationship. It can also be a bi-directional hasMany relationship, which reflect most of the time a third table in database that serve to make the link between the two models, just as tags and posts are linked in our sample database by using a table posts_tags.
