Create when not existing.
Allright, so i'm starting to get around with Cakephp, and i'm
currently working at a schoolproject in which you need to be able to
add qualities to your profile. They need to be able to add lots of
qualities (so Users <> Qualities is a HaBtM relation). The problem i'm
walking allong is that i want my app to only create a new quality if
its not existing yet. Else my app needs to pick up the quality_id of
the existing quality and create a new relation with that id. Also
people may not have the same relation twice (same quality twice). I
currently do this via the controller but i believe there is a much
more effective way of dealing with this. Could anyone help me with it?
My current code:
function addqualities() {
$this->loadModel('UsersQuality');
if(!empty($this->data)){
foreach($this->data['Quality']['name'] as $name){
$name = trim($name);
$name = strtolower($name);
$name = ucwords($name);
$result = $this->Quality->find('all', array('conditions' =>
array('Quality.name' => $name)));
if(empty($result)){
$data['Quality']['name'] = $name;
$this->Quality->create();
if($this->Quality->save($data)){
$result = $this->Quality->find('all', array('conditions' =>
array('Quality.name' => $name)));
$data['UsersQuality']['quality_id'] = $result[0]['Quality']['id'];
$data['UsersQuality']['user_id'] = $this->Auth->user('id');
$data['UsersQuality']['skill'] = 1;
$this->UsersQuality->create();
if($this->UsersQuality->save($data)){
$this->Session->setFlash('Quality added.');
}
}
}
else{
$data['UsersQuality']['quality_id'] = $result[0]['Quality']['id'];
$data['UsersQuality']['user_id'] = $this->Auth->user('id');
$data['UsersQuality']['skill'] = 1;
$result = $this->UsersQuality->find('all', array('conditions' =>
array('AND' => array('UsersQuality.user_id' => $data['UsersQuality']
['user_id'], 'UsersQuality.quality_id' => $data['UsersQuality']
['quality_id']))));
if(empty($result)){
$this->UsersQuality->create();
if($this->UsersQuality->save($data)){
$this->Session->setFlash('Quality added.');
}
else{
$this->Session->setFlash('You already have this quality.');
}
}
}
}
}
}
--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home