sql - Laravel:使用代码块在客户对象上设置字段时出现 SQL 错误

标签 sql laravel eloquent laravel-6

我收到以下错误。

SQLSTATE[HY000]: General error: 1364 Field 'code' doesn't have a default value (SQL: insert into coupons (updated_at, created_at) values (2019-12-23 14:06:02, 2019-12-23 14:06:02))

我做了一些调试,发现它来自以下代码块,但无法说出原因。

if ($customer && is_null($customer->referral_code)) {
    $coupon = new Coupon;
    $coupon->generateReferralCoupon($customer);
    $coupon->save();
    $customer->referral_code = $coupon->code;
    $customer->save();
}

添加 referral_code 的迁移如下。

class AddReferralInfoToShopUsersTable extends Migration
{
    public function up()
    {
        Schema::table('shop_users', function (Blueprint $table) {
            $table->text('referral_code')->nullable();
            $table->integer('referral_uses')->nullable();
            $table->integer('referral_revenue')->nullable();
            $table->index(['referral_code']);
        });
    }
}

最佳答案

查看错误代码,您似乎错过了对 code 属性的分配,或者您尚未将 code 放入 Coupon 模型中的可填充数组中.

很可能是这样:

$coupon->generateReferralCoupon($customer);

你应该使用:

$coupon->code = $coupon->generateReferralCoupon($customer);

关于sql - Laravel:使用代码块在客户对象上设置字段时出现 SQL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59460825/

相关文章:

laravel - whereHas 和 whereDoesntHave 在 laravel eloquent 中未按预期工作

php - Eloquent WHERE IN 使用原始查询/胶囊管理器

php - Laravel Eloquent updateOrCreate 复合键

sql - 使用表查找一行上的多个 ID

mysql - SQL 查询中大无符号整数(>1024 位)的按位运算符

php - 验证 Laravel 对象变量为空或不存在

php - A non well-formed numeric value 遇到 laravel time calculate

php - 在 Laravel 5 中使用模型事件监听器

MySQL - 如何将非唯一行转换为列并保持完整性?

sql - 如果表A中的值不为空,如何从表B中获取值