Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cake php check if record exist with custom column

Tags:

php

cakephp

Is there a way to check if record exist in cake php . I know there is a function .CakePHP 2

$this->Notes->id = $id;
if (!$this->Notes->exists())
{
    throw new NotFoundException(__('Invalid Notes'));
}

but by default it check with the column id How can i check with a custom column suppose it is note_id. my attemts are refer from here

attempt #1

if (!$this->Noteshistory->exists(['note_id'=>$id]))
{
    throw new NotFoundException(__("Invalid Note "));
}

also tried to set note_id

$this->Noteshistory->note_id = $id;
if (!$this->Noteshistory->exists(['note_id'=>$id]))
    {
        throw new NotFoundException(__("Invalid Note "));
    }

but no luck .

like image 558
Manoj Dhiman Avatar asked Jul 01 '15 10:07

Manoj Dhiman


2 Answers

hasAny is the solution -

$this->Noteshistory->hasAny(['note_id'=>$id])

will return true if found else false

hasAny is not available in version 3.x

like image 64
Sougata Bose Avatar answered Sep 18 '22 17:09

Sougata Bose


you can use hasAny():-https://api.cakephp.org/2.6/class-Model.html#_hasAny

$conditions = array(
    'note_id'=>$id
);
if ($this->Noteshistory->hasAny($conditions)){
    //do something
}

Note:- not available in 3.x version

like image 40
Anant Kumar Singh Avatar answered Sep 19 '22 17:09

Anant Kumar Singh