diff --git a/README.md b/README.md index 38fc601..061737f 100644 --- a/README.md +++ b/README.md @@ -176,12 +176,21 @@ Relationships **MY\_Model** now has support for basic _belongs\_to_ and has\_many relationships. These relationships are easy to define: + class Post_model extends MY_Model { public $belongs_to = array( 'author' ); public $has_many = array( 'comments' ); } +It's better to set primary key for _belongs\_to_ and _has\_many_ : + + class Post_model extends MY_Model + { + public $belongs_to = array( 'author' => array( 'model' => 'author_m', 'primary_key' => 'author_id' ) ); + public $has_many = array( 'comments' => array( 'model' => 'model_comments', 'primary_key' => 'post_id' ) ); + } + It will assume that a MY_Model API-compatible model with the singular relationship's name has been defined. By default, this will be `relationship_model`. The above example, for instance, would require two other models: class Author_model extends MY_Model { } @@ -191,8 +200,8 @@ If you'd like to customise this, you can pass through the model name as a parame class Post_model extends MY_Model { - public $belongs_to = array( 'author' => array( 'model' => 'author_m' ) ); - public $has_many = array( 'comments' => array( 'model' => 'model_comments' ) ); + public $belongs_to = array( 'author' => array( 'model' => 'author_m', 'primary_key' => 'author_id' ) ); + public $has_many = array( 'comments' => array( 'model' => 'model_comments', 'primary_key' => 'post_id' ) ); } You can then access your related data using the `with()` method: diff --git a/core/MY_Model.php b/core/MY_Model.php index 05add98..bf80377 100644 --- a/core/MY_Model.php +++ b/core/MY_Model.php @@ -482,6 +482,7 @@ public function relate($row) { $relationship = $key; $options = $value; + $options["primary_key"] = $this->primary_key; } if (in_array($relationship, $this->_with))