我正在使用laravel,我想将数组插入到列中,但这给了我这个错误 我不为什么
这是我的查询
DB::table('cart_product')->insert([
['product_id' => $request->product_id,'quantity' => $request->quantity, 'cart_id' => \Auth::user()->cart()->get()->first()->id, 'color_id' => $request->color, 'total_price' => $productPrice, 'specification' => $request->specification]
, ]);
这是模型
class CartProduct extends Model
{
use SoftDeletes;
protected $guarded = ['id'];
protected $dates = ['deleted_at'];
protected $table = 'cart_product';
protected $casts = ['specification' => 'array'];
}
}
这是错误的
$request->specification
这是这里的
array:4 [▼
0 => "4"
1 => "7"
2 => "8"
3 => "9"
]
给我这个错误
数组到字符串的转换
答案 0 :(得分:3)
仅当您使用雄辩的模型执行查询时,才起作用。直接使用查询生成器时,不会执行强制转换,因此您尝试将数组绑定到MySQL查询。
手动json_encode
值:
DB::table('cart_product')->insert([
['specification' => \json_encode($request->specification)]
]);
或者使用雄辩的模型:
CartProduct::create([
'specification' => $request->specification,
]);
答案 1 :(得分:0)
将数组转换为字符串
DB::table('cart_product')->insert([[
'product_id' => $request->product_id,
'quantity' => $request->quantity,
'cart_id' => \Auth::user()->cart()->get()->first()->id,
'color_id' => $request->color,
'total_price' => $productPrice,
'specification' => '[4, 7, 8, 9]'
]]);
答案 2 :(得分:0)
如果要使用DB
,则必须使用json_encode
将数组保存到数据库中
DB::table('cart_product')->insert([
[
'product_id' => $request->product_id,
'quantity' => $request->quantity,
'cart_id' => \Auth::user()->cart()->get()->first()->id,
'color_id' => $request->color,
'total_price' => $productPrice,
'specification' => json_encode($request->specification) // add json_enocde here
]
, ]);