Home » Php » php – Using the LIKE condition in a query in cakephp

php – Using the LIKE condition in a query in cakephp

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m trying to find out if a similar record already exists in the DB before I go ahead and save a record. I’ve googled and found what looks like it should work but unfortunately doesn’t. I’m new to cakephp and can’ figure out the correct query.

$this->Tape->recursive = -1;
$tapeexists = $this->Tape->find('all', array('condition'=>array('Tape.name LIKE'=>'blondie%')));
$this->set('output', $tapeexists);

If I print_r() the results in the view I can see that it just goes and gets all the results in that table, none of which have a name anything even remotely like ‘blondie’!

How to&Answers:

I think you simply misspelled conditions when doing your find:

$tapeexists = $this->Tape->find('all', array('conditions'=>array('Tape.name LIKE'=>'blondie%')));

That should give you the expected results.

For your particular goal of not allowing duplicates, I would recommend creating a validation rule on the Tape model. There is a specific built-in rule designed to avoid duplicates, so you’d probably be better off using it. Check out more information about data validation here – check out the isUnique core validation rule.