updateorcreate在laravel中引起errorexception

w46czmvw  于 2021-06-23  发布在  Mysql
关注(0)|答案(4)|浏览(361)

我编写了一个登录或注册用户的代码。我使用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 文件。
我只知道错误指向updateorcreate函数的secound参数。
谢谢你的帮助

o0lyfsai

o0lyfsai1#

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

看看它是否适合你。

l5tcr1uw

l5tcr1uw2#

我终于解决了。通过将created和update列添加到表中,并将这两个coulmn添加到$guarded中,模型如下 protected $guarded = array('id','CREATED_AT','UPDATED_AT'); 然后问题解决了
谢谢你的帮助

rbpvctlc

rbpvctlc3#

如果你看一下laravel文档,你只是在使用 updateOrCreate 方法错误。请看下面的飞行示例。
在您的情况下,应该如下所示:

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

ukxgm1gy4#

如果你看到 Model 类的laravel框架代码,您可以注意到 updated_at 仅在不存在时存储 dirty .

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

但是 isDirty 方法只检查空值。

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;
}

那就换一个吧 falseNULL .

相关问题