【发布时间】:2021-11-09 05:21:29
【问题描述】:
我知道这个问题是重复的,但尝试了这些问题的几个答案对我没有任何帮助。
总之我有这个存储方法:
public function store(Request $request)
{
$selected_products = json_decode($request->selectedproducts);
$cart = new Cart();
$cartprods = CartProd::hydrate( $selected_products );
// This sums all the end costs to get a total cost
// And saves the cart so that its id is not null
$final_cost = 0;
foreach ($cartprods as $prod) {
$final_cost += $prod->cost;
}
$cart->cost = $final_cost;
$cart->user_id = Auth::user()->id;
$cart->save();
foreach ($cartprods as $prod) {
$prod->cart_id = $cart->id;
$og_product = Product::FindOrFail($prod->product_id);
$og_product->amount -= $prod->amount;
$og_product->save();
$prod->save();
dd($prod->save());
}
return redirect()->route('cart');
}
执行上面的 dd 显示为 true,但进入我的数据库并执行 select * 表示它是一个空集。
这是我的 CartProd 模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CartProd extends Model
{
use HasFactory;
protected $table = 'cartprod';
protected $primaryKey = 'id';
protected $fillable = [
'unit_price',
'amount',
'discount',
'cost',
'cart_id',
'product_id',
];
public function cart()
{
return $this->belongsTo(Cart::class, 'cart_id');
}
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
}
因为它可能有用,所以这些是用于迁移表的命令(它们在自己的迁移文件中,所以那里没有问题):
Schema::create('cartprod', function (Blueprint $table) {
$table->id();
$table->decimal('unit_price',9,2);
$table->integer('amount');
$table->integer('discount');
$table->decimal('total_cost',9,2);
$table->timestamps();
});
Schema::table('cartprod', function (Blueprint $table) {
$table->foreignId('cart_id')->references('id')->on('cart');
});
Schema::table('cartprod', function (Blueprint $table) {
$table->foreignId('product_id')->references('id')->on('product');
});
在搜索答案后,我发现了其他几个对我没有帮助的问题,例如 $primaryKey 与数据库上的名称匹配(确实如此),或者其他不适合我的模型的。非常感谢您的帮助!
【问题讨论】:
-
我们可以看看您发送到商店功能的
$request->selectedproducts中的内容吗? -
@Lyzvaleska 我很抱歉花了这么长时间才回复! $request->selectedproducts 发送要购买的物品数组。例如:[{"unit_price":5,"amount":4,"discount":0.95,"cost":19,"cart_id":null,"product_id":1,"product":{"id": 1,"name":"Sticker","amount":7,"price":"5.00","created_at":"2021-09-14T00:37:09.000000Z","updated_at":"2021-09- 14T23:33:07.000000Z"}},{"unit_price":10,"amount":1,"discount":1,"cost":10,"cart_id":null,"product_id":2,"product" :{"id":2,"name":"Pencil","amount":5,"price":"10.00","created_at":"2021-09-14T00:37:09.000000Z","updated_at" :"2021-09-14T23:24:05.000000Z"}}]
-
如果您在购物车中添加 4 个 5% 折扣的贴纸和一支没有折扣的铅笔,它们会以数组的形式发送,其方法 json_decode 将其从 json 转换为正确的数组,然后是 CartProd::hydrate 是什么使它成为 CartProds 的集合。
-
您是否尝试过以传统方式填充模型而不是水合器?我不得不承认我从来没有遇到过
::hydrate(),而且我在你的代码中看不到任何可能是错误的东西。 -
@Lyzvaleska 你说的完全正确!我以前也从未遇到过 hydrate 函数,我认为它可以节省我一些时间,但似乎没有什么比老式的 foreach 循环更好的了!