Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 { }
Expand All @@ -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:
Expand Down
1 change: 1 addition & 0 deletions core/MY_Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,7 @@ public function relate($row)
{
$relationship = $key;
$options = $value;
$options["primary_key"] = $this->primary_key;
}

if (in_array($relationship, $this->_with))
Expand Down