Category: Models & ORM

Q: Table::get($name)->hasAny(['key' => 'value'] is not working in cakephp 3

Cake shows error unknown method "hasAny" when checking a record exists or not. Neither this..

TableRegistry::get('Posts')->hasAny(['Post.id' => 1]);

or that

$this->Posts->hasAny(array(['Post.id' => 1']));

works. The version of cakephp I'm using is 3.2.

SOLVED
1 Answers
user
Kristi

137

Accepted by Kristi

Hi Kristi:

The hasAny function is deprecated in Cakephp 3. The right way to check if a record exists or not is to do:

TableRegistry::get('Posts')->exists(['Posts.id' => 1]); //notice: 'Posts.id' => 1 or 'id' => 1 either will do

You can check this link about upgrading to Cakephp 3: Model::hasAny(array $conditions) is now Table::exists(array $conditions)

And of course if you prefer the old fashion way:

$this->Posts = TableRegistry::get('Posts');

$this->Posts->exists(['Posts.id' => 1]);

//or check data existence
if ($this->Posts->exists(['Posts.id' => 1]) {
  
  //do something
}

//and so on.. e.g. creating new entity
$entity = $this->Posts->newEntity($data);
$this->Posts->save($entity);

Created: 29 Aug '16

Last Reply: 29 Aug '16

Replies: 1

Views: 1550

Votes: 0

Welcome to Aero Coding!

Aero Coding is a CakePHP-focused Q&A community for professional and enthusiast cake bakers. It's built and run by you as part of the community.


Join Now Tour

Download Cakephp

Start baking your own CakePHP application!


Cakephp All Versions