[英]Insert array column query builder laravel
I am using laravel and I want to insert an array to a column but it gives me this error I do not why我正在使用 laravel,我想将一个数组插入一列,但它给了我这个错误我不知道为什么
here is my query这是我的查询
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]
, ]);
and here is model这是模型
class CartProduct extends Model
{
use SoftDeletes;
protected $guarded = ['id'];
protected $dates = ['deleted_at'];
protected $table = 'cart_product';
protected $casts = ['specification' => 'array'];
}
}
and error is for this错误是为此
$request->specification
here is a dd of this这是一个 dd
array:4 [▼
0 => "4"
1 => "7"
2 => "8"
3 => "9"
]
gives me this error给我这个错误
Array to string conversion
数组到字符串的转换
Casts only work when you use Eloquent Models to execute the queries.仅当您使用 Eloquent 模型执行查询时,转换才有效。 When you use the Query Builder directly, your casts are not executed, so you are trying to bind an array to a MySQL query.
当您直接使用查询生成器时,不会执行您的强制转换,因此您正在尝试将数组绑定到 MySQL 查询。
Either manually json_encode
the value:要么手动
json_encode
值:
DB::table('cart_product')->insert([
['specification' => \json_encode($request->specification)]
]);
Or use the eloquent model:或者使用 eloquent 模型:
CartProduct::create([
'specification' => $request->specification,
]);
Convert Your Array to string将您的数组转换为字符串
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]'
]]);
If you want to use DB
then you have to user json_encode
to save array in your database如果您想使用
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
]
, ]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.