我想知道,有没有一个功能可以让我立即检查数据库中的记录是否存在?
现在我正在使用以下代码来检测记录是否存在,但我可以想象有一种更简单/更好的方法。
$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
}
有没有类似的东西:
$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
}
好的,是的。它叫做
exists()
,但我需要相同的,但带有参数,这样我就可以在检查中添加我自己的条件。
我搜索过谷歌,但找不到任何关于此的主题。嗯,有很多关于 php 和 mysql 的内容,但没有关于 cakephp 的内容。我需要一个具体的蛋糕答案。
感谢您的宝贵时间:)
您正在寻找的是 Model::hasAny
用途:
$conditions = array(
'User.id' => $this->Session->read('User.id'),
'User.security_key' => $this->Session->read('User.key')
);
if ($this->User->hasAny($conditions)){
//do something
}
对于 CakePHP 3,您可以使用 contains() 方法,具有类似的输入值。
exists(arrayArrayAccess $conditions): bool
Returns true if there is any record in this repository matching the specified conditions.
https://api.cakephp.org/3.1/class-Cake.ORM.Table.html#exists()