Welcome Guest, Not a member yet? Register   Sign In
How to save relationship in datamapper orm?
#1

[eluser]Unknown[/eluser]
Hi all,

I have problems trying to save the relationship with the following database and code. Kindly refer to the controller code as that's the area which I have problems saving data. I'm new to the datamapper ORM.

DB
Code:
accounts
  id
  username
  password

posts
  id
  title
  content

posts_accounts
  post_id
  account_id

Models for both Posts and Accounts
Code:
class Account extends DataMapper {
public $has_many = array('post' => array('join_table' => 'posts_accounts'));

public function __construct() {
  
  // model constructor
  parent::__construct();
}
}
Code:
class Post extends DataMapper {
public $has_many = array('account' => array('join_table' => 'posts_accounts'));

var $validation = array(
  'title' => array(
   'label' => 'Title',
   'rules' => array('required')
  ),
  'content' => array(
   'label' => 'Content',
   'rules' => array('required')
  ),
);

public function __construct() {
  
  // model constructor
  parent::__construct();
}
}

Controller
Code:
class Posts extends CI_Controller {
  public function __construct() {
        parent::__construct();
        $this->load->model('Account');

        // load url helper
        $this->load->helper('url');
  $this->load->helper('form');
    }

    function index($offset=0) {

        $post= new Post();

        $post->order_by('title');        
        $data['posts'] = $post->get()->all;        
      

        $this->load->view('posts/index', $data);        
    }

function create() {
  // this is the part where I have problems saving.
  $post = new Post();
  $account = new Account();
  $results = $this->input->post();

  $account->where('id', 1)->get();

  $post->title = $results['title'];
  $post->content = $results['content'];
  $post->validate()->get();
  
  if ($post->save($account)) {
   echo 'successfully created';
  }
  else {
   echo '<p>' . $post->error->string . '</p>';
  }

  $this->load->view('posts/create');
}
}

I have a few thoughts in mind. Should I try to create a foreign key in posts table such as account_id instead of using posts_accounts? And even I have managed to save the relationship, how do I extract the data in views? Appreciate any help from anybody who can help me sort this out.




Theme © iAndrew 2016 - Forum software by © MyBB