cakephp contain twice model association -
i have fetch info posts
table
which has foreign keys
( category_id
references categories.id
created_by
references users.id
, updated_by
references users.id
)
i can fetch created_by
username
not both
$this->post->behaviors->load('containable'); $this->paginate = array( 'conditions' => array('post.category_id' => $id), 'order' => array('title'), 'contain' => array( 'user'=>array( 'fields'=>array('id','first_name','last_name','username'), 'conditions' => array('user.id = post.created_by') ), //posts table has 2 fields(created_by & updated_by) associated users table //'user'=>array( // 'fields'=>array('id','first_name','last_name','username'), // 'conditions' => array('user.id = post.updated_by') // ), 'category'=>array( 'type'=>array( 'fields'=>array('id','type_name') ) ), ) );
//post model
public $belongsto = array( 'user'=> array( 'classname' => 'user', 'foreignkey' => 'created_by', 'foreignkey' => 'updated_by' ), );
//user model
public $hasmany = array( 'post' => array( 'classname' => 'post', 'foreignkey' => array('created_by','updated_by'), ), );
how show both , alias both users (created_by
& updated_by
)
first need define 2 relationships in post model
public $belongsto = array( 'createduser'=> array( 'classname' => 'user', 'foreignkey' => 'created_by' ), 'updateduser'=> array( 'classname' => 'user', 'foreignkey' => 'updated_by' ) );
now create converse relationships in user model.
public $hasmany = array( 'createdposts' => array( 'classname' => 'post', 'foreignkey' =>'created_by' ), 'updatedposts' => array( 'classname' => 'post', 'foreignkey' => 'updated_by' ), );
then find()
$this->post->behaviors->load('containable'); $this->paginate = array( 'conditions' => array('post.category_id' => $id), 'order' => array('title'), 'contain' => array( 'createduser'=>array( 'fields'=>array('id','first_name','last_name','username') ), 'updateduser'=>array( 'fields'=>array('id','first_name','last_name','username') ), 'category'=>array( 'type'=>array( 'fields'=>array('id','type_name') ) ), ) );
cakephp associations containable
No comments:
Post a Comment