【问题标题】:updateOrCreate cause ErrorException in laravelupdateOrCreate 在 laravel 中导致 ErrorException
【发布时间】:2018-10-08 08:58:40
【问题描述】:

我写了一个代码来登录或注册用户。如果用户不存在,我使用 updateOrCreate 函数添加用户,如果用户存在,则更新名称为验证码的列

控制器

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 函数的第二个参数。

感谢帮助

【问题讨论】:

  • 我已经回答了。请检查并告诉我它是否适合您。谢谢

标签: php mysql laravel model


【解决方案1】:
$phone=Input::get('phone');
$code=rand(1001,9999);
user::updateOrCreate(
    ['phone' => $phone]
    ['verifcode' => $code]        
);

看看它是否适合你。

【讨论】:

  • 谢谢,但我想先检查手机而不是验证码
【解决方案2】:

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

感谢帮助

【讨论】:

  • 无需添加 created_at、updated_at 列。只需在模型中执行 false 即可: public $timestamps = false;我想你已经添加了这两列。
  • 我也改成 false 但错误仍然存​​在...我测试了所有方法但只添加了修复它的列
【解决方案3】:

如果您查看Laravel documentation,您只是使用了updateOrCreate 方法错误。看看那里的飞行示例。

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

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

【讨论】:

  • 什么都没发生...timeStmp 有默认值,不需要值
  • 你想做什么?从您的代码中,我了解到您想检查具有给定电话号码的用户是否存在并更新代码?或者您是否要检查具有给定电话号码和代码的用户是否存在?在这种情况下,你的逻辑有问题。
  • 是的,我想检查具有给定电话号码的用户是否存在并更新代码...但是错误来自这两列...Update_at 和 Created_at 没有别的
【解决方案4】:

如果你看到 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;
}

所以只需将false 替换为NULL

【讨论】:

  • 你最好修复那个another error,你的解决方案不好。
猜你喜欢
  • 2017-07-30
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
  • 2022-11-07
相关资源
最近更新 更多