Reputation: 718
I am working on models using cakephp. I have two models, the post model; which contains a $hasMany relationship with the tags model. I want the tags name value to be a unique. This is to remove any data redundancy. I want to make it searchable via a AJAX like search box for the tags. I need to be able to automatically create the tags on the fly, but only if they have not already been created. How do i achieve this with CakePHP 2.6.1?
Example: I have created two tables:
tags:
id name post_id
posts:
id title url content
Upvotes: 1
Views: 102
Reputation: 34837
In order to make sure that the name
value of any tag is unique, simply add a validation rule to the Tag
model for the name field. There is a specific isUnique validation rule. In your app/Model/Tag.php
file, add this:
public $validate = array(
'name' => array(
'rule' => 'isUnique',
'message' => 'This tag already exists.'
)
);
That will cause any save operation on the Tag model with a duplicate tag name to fail with the error message you set in the model.
To make it ignore any duplicates, slightly change the way your save works. Add something like this to your Controller logic:
foreach ($this->request->data['Tags'] as $tagData) {
$this->Tag->set($tagData);
if ($this->Tag->validates()) {
$this->Tag->create();
$this->Tag->save($tagData);
}
}
Upvotes: 2