[eluser]WanWizard[/eluser]
[quote author="animatora" date="1340803299"]Ok I understand this, but what if I want to use creator rather than user for relation name ? How can I mask the user behind creator ? I can't change the database, it has been setup like this? Is it possible to do this trick ?
$post->creator makes much more sense, than $post->user [/quote]
If you dump a model object, you'll see that internally Datamapper will expand simple definitions to advanced definitions, so you can see which defaults are being used.
For example, in this case if you do user $has_one('post'), this will be generated:
Code:
array (size=1)
'post' =>
array (size=8)
'class' => string 'post' (length=4)
'other_field' => string 'user' (length=4)
'join_self_as' => string 'user' (length=4)
'join_other_as' => string 'post' (length=4)
'join_table' => string '' (length=0)
'reciprocal' => boolean false
'auto_populate' => null
'cascade_delete' => boolean true
This says:
- array key: my User object has a related object called 'post'
- class: this object is defined by the class 'post'
- other_field: in the the class 'post', the relation back to me is defined as 'user'
- join_self_as: foreign key for my side of the relation (_id is appended, so 'user_id')
- join_other_as: foreign key for the other side of the relation (_id is appended, so 'post_id')
- join_table: table containing the foreign keys (required in many-many, optional for others)
- reciprocal: when true and a self-referencing relation, make the relation both ways
- autopopulate: if true, fetch this relations objects when the parent is fetched
- cascade_delete: if true, delete related objects when you delete the parent
So if you just want to name the relation 'creator', change the array key, and set class to 'post'. And in the post model you set the 'other_field' to 'creator'. Leave the other fields as defined above (any foreign key will still be called 'post_id' for example).
Although the foreign keys are defined for both tables, they will only used when needed, Datamapper is smart enough to figure out which to use.
For example, if you have a one-one relation, the foreign key can be in either table. Or you can have a one-one relation that uses a join table (in which case both FK's are needed).
I hope this helps.