Laravel 主键上的数据库更新适用于原始数组,但不适用于变量

Laravel DB update on primary keys works with a raw array but not with a variable

我最初想使用 Eloquent:

$product->quantity_discounts()
->where('min_amount', $discount['min_amount'])
->where('user_id', $discount['user_id'])
->where('group_id', $discount['group_id'])
->update($discount);

但 Eloquent 不支持复合主键 (https://github.com/laravel/framework/issues/5355)。

我的代码,使用查询生成器:

DB::table('quantity_discounts')
->where('min_amount', $discount['min_amount'])
->where('user_id', $discount['user_id'])
->where('group_id', $discount['group_id'])
->where('product_id', $id)
->update($discount);

$折扣:

[
    "min_amount" => "2",
    "price" => "20",
    "user_id" => "1",
    "group_id" => "0"
]

唯一更改的字段是价格。所有其他字段都是主键约束的一部分。

但是,完全传递 $discount 中的内容是有效的。查询构建器似乎不会为主键批量分配值。

查询update($discount)

update `quantity_discounts` set `min_amount` = ?, `price` = ?, `user_id` = ?, `group_id` = ? where `min_amount` = ? and `user_id` = ? and `group_id` = ? and `product_id` = ?

查询update([...])

update `quantity_discounts` set `min_amount` = ?, `price` = ?, `user_id` = ?, `group_id` = ? where `min_amount` = ? and `user_id` = ? and `group_id` = ? and `product_id` = ? 

查询是相同的。阵列是相同的。 [] 有效,但 $discount 无效。

如果更改任何主键字段,价格也不会更改。什么都不会改变。如果只改变价格,价格就会改变。

尽管使用原始数组 [] 有效:

而且数组确​​实相同:

这可能是某种批量分配保护吗? ["min_amount" => $discount["min_amount"], ...] 也没用。我已将所有字段设置为 $fillable,但这是针对 Eloquent,而不是查询构建器。

在变量 $discount 的情况下,我看到一个逻辑错误,这可能是原因,您正在寻找新的 ID 而不是旧的,如果产品只有一个折扣,那么更新不起作用,因为不存在新 ID 的折扣,但如果您只更改价格或数量,则更新有效,因为 ID 没有更改,因此您需要按旧 ID 搜索并使用变量更新 $discount.

DB::table('quantity_discounts')
->where('min_amount', $discount['min_amount'])
->where('user_id', $old['user_id'])
->where('group_id', $old['group_id'])
->where('product_id', $id)
->update($discount);

希望对您有所帮助!