php Cakephp 检查记录是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11996823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cakephp check if record exists
提问by Jelmer
I am wondering, is there a function that allows me to check instantly if a record in the database exists?
我想知道,是否有一个功能可以让我立即检查数据库中的记录是否存在?
Right now I am using the following piece of code to detect if a record exists, but I can imagine there is a simpler/better way.
现在我正在使用以下代码来检测记录是否存在,但我可以想象有一种更简单/更好的方法。
$conditions = array(
'conditions' => array(
'User.id' => $this->Session->read('User.id'),
'User.activation_key' => $this->Session->read('User.key')
)
);
$result = $this->User->find('first', $conditions);
if (isset($result['User'])){
//do something
}
Is there something like:
有没有类似的东西:
$conditions = array(
'conditions' => array(
'User.id' => $this->Session->read('User.id'),
'User.security_key' => $this->Session->read('User.key')
)
);
if ($this->User->exists($conditions)){
//do something
}
Okay, yes there is. It's called exists(), but I need the same, but with parameters, so I can add my own conditions to the check.
好的,是的。它被称为exists(),但我需要相同的,但带有参数,因此我可以将自己的条件添加到检查中。
I have searched google, but I can't find any topic about this. Well, a lot about php and mysql, but not about cakephp. I need a cake specific answer.
我已经搜索过谷歌,但我找不到任何关于此的主题。嗯,很多关于 php 和 mysql,但不是关于 cakephp。我需要一个蛋糕的具体答案。
Thanks for your time :)
谢谢你的时间 :)
回答by tigrang
What you are looking for is Model::hasAny
您正在寻找的是Model::hasAny
Usage:
用法:
$conditions = array(
'User.id' => $this->Session->read('User.id'),
'User.security_key' => $this->Session->read('User.key')
);
if ($this->User->hasAny($conditions)){
//do something
}

