save() returning false, but with no error in CakeP

2019-01-23 01:25发布

My debug value is set to 2, and it's displaying all the queries, except the one I need.

I have an Items controller method that is calling this method in the User model (Item belongsTo User):

function add_basic($email, $password) {
    $this->create();

    $this->set(array(
        'email' => $email,
        'password' => $password
    ));

    if($this->save()) {
        return $this->id;
    }
    else {
        return false;
    }
}

I have confirmed that $email and $password are being passed into the function correctly (and are populated with legit data). email and password are the names of the fields in the User model.

I have also confirmed that on $this->save() it is returning false, but when I view the page where this occurs, the query is not being printed in the debug, and there is no error being thrown, so I have no idea whats going wrong.

Any ideas on how I can see the error, or why the query doesn't seem to be getting executed?

It's weird, cause right after this, I have another model saving data to it in the exact same fashion, it goes off without a hitch.

7条回答
\"骚年 ilove
2楼-- · 2019-01-23 01:36

Make sure to check your tables:

  • Does ID have auto increment enabled?
  • Is id your primary key?

the auto_increment issues killed me. Easy way to check: if any of your rows have ID = 0, auto_increment is likely disabled.

查看更多
Animai°情兽
3楼-- · 2019-01-23 01:39

Try this:

if ($this->save()) {
    return $this->id;
}
else {
    var_dump($this->invalidFields());
    return false;
}
查看更多
女痞
4楼-- · 2019-01-23 01:42

Have you got a beforeValidate() or beforeSave() method in the model or app model? Ifso, are they returning true? Failing that, use a debugger, set a break point in your IDE at the top of cake/libs/models/model.php save() method and step through the code until it returns false. Failing that add die('here'); calls.

查看更多
虎瘦雄心在
5楼-- · 2019-01-23 01:50

This will probably give you the info you need (assuming it's not saving because of invalid data, of course):

if(!$this->save()){
    debug($this->validationErrors); die();
}
查看更多
孤傲高冷的网名
6楼-- · 2019-01-23 01:50

The other situation where CakePHP fails to report any $this->Model->validationErrors and no other errors is potentially when $this->request->data isn't as Cake expects and is simply ignoring your data, not saving, no validation errors. For example if your data was provided by DataTables you might see this format $this->request->data[0]['Model']['some_field'].

$this->Model->save($this->request->data[0]) will work however.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-23 01:57

@cakePHP 3.6 : After you save an entity any validation errors will be stored on the entity itself. It can read by getErrors() method.

\Cake\Log\Log::debug($this->ModelName->getErrors());
Example: log::debug($contactRelationship->getErrors());

Ref: https://book.cakephp.org/3.0/en/orm/entities.html

查看更多
登录 后发表回答