Welcome Guest, Not a member yet? Register   Sign In
ActiveRecord for CodeIgniter: Rails-style model interactions
#37

[eluser]chrisj[/eluser]
Any more luck with other relations (has_many, has_one, belongs_to)? Using the suggestion before, I've been hacking a little bit, but would like input.

Here's my new _fetch_related:
Code:
function _fetch_related($table, $inflected)
{
  $inflected = ($inflected) ? $inflected[0] : substr($table, 0, -1);

  if( array_search($table, $this->_belongs_to) ) {
        $foreign_key = $table . '_id';
        $query = $this->db->query('SELECT * FROM ' . $inflected . ' WHERE id = ' . $this->$foreign_key);
    }
  else if( array_search($table, $this->_has_many) || array_search($table, $this->_has_one) ) {
      $query = $this->db->query('SELECT * FROM ' . $table . ' WHERE '. $this->_table .'_id = ' . $this->id);
  }
  else if( array_search($table, $this->_has_and_belongs_to_many) ) {
    $relationship_table = ($this->_table < $table) ? $this->_table . '_' . $table : $table . '_' . $this->_table;
    $query = $this->db->query('
        SELECT
        ' . $table . '.*
        FROM
        ' . $table . '
        LEFT JOIN
        ' . $relationship_table . '
        ON
        ' . $table . '.id = ' . $inflected . '_id
        LEFT JOIN
        ' . $this->_table . '
        ON
        ' . $this->_table . '.id = ' . $this->_class_name . '_id
        WHERE
        ' . $this->_table . '.id = ' . $this->id
        );
  }

  eval('$this->' . $table . ' = $query->result();');            
}

And then add this to the ActiveRecord constructor to prevent errors if you don't specify relations in the child class:
Code:
$this->_belongs_to = array();
$this->_has_many = array();
$this->_has_one = array();
$this->_has_and_belongs_to_many = array();

So then the model looks like this (traditional blog example):
Code:
class Post extends ActiveRecord {
    function __construct()
    {
        parent::ActiveRecord();
        $this->_class_name = strtolower(get_class($this));
        $this->_table = get_class($this).'s';
        $this->_columns = $this->discover_table_columns();

        $this->_belongs_to = array('blog','category','post_type','user');
        $this->_has_many = array('comments','images');
        $this->_has_and_belongs_to_many = array('tags');
    }
}

And then in my controller I can do this:
Code:
$post = $this->Post->find($id);
$post->fetch_related_blog();
$post->fetch_related_category();
$post->fetch_related_post_type();
$post->fetch_related_user();
$post->fetch_related_comments();
$post->fetch_related_images();
$post->fetch_related_tags();

This seems to work okay.

I haven't tackled create_relationship yet.

I've also been working on putting the CI validation procedures into the model (ala RoR) but that's another issue.


Messages In This Thread
ActiveRecord for CodeIgniter: Rails-style model interactions - by El Forum - 09-28-2007, 10:59 AM



Theme © iAndrew 2016 - Forum software by © MyBB