I am using CakePHP 1.3 with MySQL and run in a tight loop with code like:
if ($this->Model->find('count', array('conditions' => array('Model.name' => 'name'))) == 0)
{
$this->Model->create();
$this->Model->save(array('Model' => array('name' => 'name')));
}
$data = $this->Model->find('first', array('conditions' => array('Model.name' => 'name')));
However, at times $data comes out to be NULL; in other words, the record doesn't exist even though I do create/save a new record if it doesn't exist to begin with.
Is there some delay between the time the record gets created and when it is available?
Any help is greatly appreciated.
EDIT 1 I should point out that I do make sure the call to Model->save() succeeds before continue.
if (!$this->Model->save(array('Model' => array('name' => '开发者_JAVA百科name'))))
$this->error('Save failed');
Thank you.
I don't think so, on MySQL level whenever the insert is finished, the newly created record can be used instantly. I've been using MySQL for years and I've never got this problem. As far as I know, the commands are added to a queue and are executed in a FIFO (First In First Out) system on default.
You can always rewrite your code a bit:
if ($this->Model->find('count', array('conditions' => array('Model.name' => 'name'))) == 0)
{
$this->Model->create();
if ($this->Model->save(array('Model' => array('name' => 'name'))))
{
$data = $this->Model->find('first', array('conditions' => array('Model.name' => 'name')));
/* or better: */
$data = $this->Model->findByName('name');
/* or rather use: */
$data = $this->Model->find('first', array('conditions' => array('Model.id' => $this->Model->id)));
/* or even better, try this: */
$data = $this->Model->read();
}
}
Maybe you have some validation rules that are preventing to save, try this
if (!$this->Model->save(array('Model' => array('name' => 'name')))) {
pr($this->Model->validationErrors);
}
if the pr() shows something, then you'll find the issue
精彩评论