Laravel模型的save()和update()无法保存数据

5

Laravel 5.7

你好,我在 Stack Overflow 上查找了许多可能的答案,但没有得出结论。我正在通过简单的检查更新一个 patron 表中的简单整数值并且它没有更新数据库。我已经尝试在模型上使用 save() 和 update() 方法。

没有任何错误或异常显示,并且 save() 和 update() 方法返回 true。

代码:

控制器类使用模型并更新数据:

$patron_coupon = PatronCoupons::where('owner',$patron_id)->where('coupon_id',$active_coupon['coupon_id'])->first();

if($patron_coupon->current_uses > $active_coupon['max_uses'])
    $patron_coupon->current_uses = $active_coupon['max_uses'];
// if i echo $patron_coupon->current_uses here, it will show that this value has changed ( good )

$patron_coupon->current_uses = $active_coupon['max_uses'] - $patron_coupon->times_used;
if($patron_coupon->current_uses < 0)
    $patron_coupon->current_uses = 0;

// this doesnt work 
$patron_coupon->save();
// this doesnt work either 
$patron_coupon->update($patron_coupon->toArray());
// if i echo current_uses here, the value goes back to what it was before being set.

模型类:

class PatronCoupons extends Model
{
    protected $table = 'patron_coupons';
    protected $primaryKey = 'owner';
    public $timestamps = false;
    protected $fillable = ['times_used','current_uses','settings_version'];
}

迁移文件:

Schema::create('patron_coupons', function (Blueprint $table) {
    $table->string('owner');                                // patron id that 'owns' this coupon
    $table->unsignedInteger('coupon_id');                   // id of this coupon
    $table->unsignedInteger('current_uses')->default(0);    // the amount of uses this patron has for this coupon
    $table->unsignedInteger('settings_version')->nullable();// last settings version fetch
    $table->unsignedInteger('times_used')->default(0);      // amount of times this coupon has been used
});

请帮帮我,我已经在桌子上磕了几个小时了!!!!


你能否也加上一行代码:dd($patron_coupon->current_users); 理想情况下,你将得到20。另外我还想知道的是,如果你手动更改current uses的db值,在检索后转储该值,是否能确保从数据库中获取了正确的值。 - PhxSteve
尝试使用静态函数更新,而不是 update([ 'current_uses' => 12 ]) - Jonathan K
@JonathanK 这个方法可以正常工作并更新数据库。我现在可以将其用作可行的解决方案,但为什么这样做可以工作而不是只使用 save() 呢? - Zac
很高兴它能正常工作。我真的不知道为什么它不能工作。你可以删除vendorcomposer.lock文件,然后再次运行composer install。也许会起作用。 - Jonathan K
@JonathanK 刚试过了,运行了 composer install,但仍然不能与我的原始代码一起正常工作。我将坚持使用静态函数,这是我真正需要的。谢谢大家。 - Zac
显示剩余3条评论
3个回答

3
你可以尝试以下任意一种方法:
  1. Try using static update function instead

    PatronCoupons::update([
        // updates here
    ]);
    
  2. Remove your vendor folder and composer.lock file. Then run composer install to refresh your vendor file


1
获取记录
$patronCoupons = PatronCoupons::find($id);

$patronCoupons->update([
    'times_used' => 'value',
    'current_uses' => 'value',
    'settings_version' => 'value'
]);

如果您的提交数据中有相同的输入名称,则直接使用。
$post = $request->all();

$patronCoupons = PatronCoupons::find($id);

$patronCoupons->update($post);


0
请确保将此代码放在导致错误的表单中。
'enctype' => 'multipart/form-data'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接