5

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 .

Community
  • 1
  • 1
Manoj Dhiman
  • 5,096
  • 6
  • 29
  • 68
  • Would be a good idea to look at [the method signature for the methods you're calling](https://github.com/cakephp/cakephp/blob/2.6.8/lib/Cake/Model/Model.php#L2889) - should be obvious that passing `['note_id'=>$id]` won't work (in fact, that would try to find a notes-history record with the id `$id`). – AD7six Jul 01 '15 at 10:45

2 Answers2

13

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

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
  • 1
    I would say hasAny is _a_ solution - a count works just as well, which after all is [all that method does](https://github.com/cakephp/cakephp/blob/2.6.8/lib/Cake/Model/Model.php#L2907-L2915). Note that hasAny doesn't exist in the current version of CakePHP. – AD7six Jul 01 '15 at 10:42
  • @AD7six . You are right. `hasAny` is not available in `V 3`. `COUNT` will help there. – Sougata Bose Jul 01 '15 at 10:44
  • 2
    I meant more along the lines of: Don't recommend/get-used to using functions that don't exist in a future version - it makes any future upgrade a bit harder. Methods like hasAny don't really help since they just hide that it's a count (personally I don't think I've ever used hasAny), and so were removed. It's not wrong, just an observation+recommendation. – AD7six Jul 01 '15 at 10:50
2

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

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98