繁体   English   中英

updateOrCreate在Laravel中导致ErrorException

[英]updateOrCreate cause ErrorException in laravel

我编写了用于登录或注册用户的代码。我使用updateOrCreate函数添加用户(如果不存在),如果用户存在,则更新名为verifcode的列

控制者

users Table:
id(auto increment primary key)|phone|verifcode|timeStmp
---------------------------------
    $phone=Input::get('phone');
    $code=rand(1001,9999);
    $user = new user;
    $user = array('phone'=>$phone);
    user::updateOrCreate($user,['verifcode' => $code]);

模型:

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    protected $table = 'users';
    protected $fillable = array('phone', 'verifcode','timeStmp');
    protected $guarded = array('id');
    protected $primaryKey = "id";
    public $incrementing = false;
    const CREATED_AT= false;
    const UPDATED_AT = false;

}

与此代码,我有以下错误: array_key_exists(): The first argument should be either a string or an integer指向vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Concerns\\HasAttributes.php文件array_key_exists(): The first argument should be either a string or an integer

我只知道错误指向UpdateOrCreate函数的secound参数。

感谢帮助

如果看一下Laravel文档 ,您只是在使用updateOrCreate方法错误。 看那里的航班示例。

在您的情况下,它应如下所示:

$phone = \Input::get('phone')
$code  = rand(1001, 9999);
$user  = User::updateOrCreate(
           ['phone' => $phone],
           ['verifcode' => $code, 'timeStmp' => \Carbon::now()->timestamp]
         );

如果您在laravel框架代码的Model类中看到,您会注意到, updated_at仅在不dirty时存储。

    if (! $this->isDirty(static::UPDATED_AT)) {
        $this->setUpdatedAt($time);
    }

但是isDirty方法仅检查null。

public function isDirty($attributes = null)
{
    $dirty = $this->getDirty();

    if (is_null($attributes)) {
        return count($dirty) > 0;
    }

    if (! is_array($attributes)) {
        $attributes = func_get_args();
    }

    foreach ($attributes as $attribute) {
        if (array_key_exists($attribute, $dirty)) {
            return true;
        }
    }

    return false;
}

因此,只需将false替换为NULL

$phone=Input::get('phone');
$code=rand(1001,9999);
user::updateOrCreate(
    ['phone' => $phone]
    ['verifcode' => $code]        
);

看看是否适合您。

终于我解决了。 通过向表中添加Created_at和Update_at列,并将这两个同伴添加到$ guarded的模型中,例如: protected $guarded = array('id','CREATED_AT','UPDATED_AT'); 然后解决问题

感谢帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM