繁体   English   中英

Laravel DB对主键的更新适用于原始数组,但不适用于变量

[英]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不变,因此您需要按旧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);

我希望这可以帮助你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM