我的控制器中有 store 方法,它返回以下错误:错误安慰Preview tabexception: "ErrorException"file: "C:\........\vendor\laravel\framework\src\Illuminate\Support\Str.php"line: 419message: "Array to string conversion"安慰Response tab { "file": "C:\\........\\app\\Http\\Controllers\\Api\\Front\\CartController.php", "line": 380, "function": "save", "class": "Illuminate\\Database\\Eloquent\\Model", "type": "->" },代码public function checkout(Request $request){ $user = auth('api')->user(); $cartItems = CartStorage::where('user_id', $user->id)->get(); $address = AddressUser::where('id', $request->input('address'))->first(); foreach($cartItems as $item) { $cartData = $item->cart_data; // add to orders table try { $order = new Order(); $order->ordernu = 'Si-'.mt_rand(1000000000, 9999999999); $order->user_id = $user->id; $order->order_data = $cartData; $order->quantity = $cartData['quantity']; $order->price = $request->input('totalPrice'); $order->courier = $request->input('courier'); $order->courier_service = $request->input('courierService'); $order->shippingcode = $request->input('shippingcode'); $order->shipping_price = $request->input('shippingPrice'); $order->address = $address->address; $order->kecamatan = $address->kecamatan; $order->kelurahan = $address->kelurahan; $order->kota = $address->kota; $order->provinsi = $address->provinsi; $order->postalcode = $address->postalcode; $order->weight = $request->input('weight'); $order->phone = $request->input('phone'); $order->buyer_name = $user->name; $order->buyer_email = $user->email; $order->note = $request->input('note'); $order->received = false; $order->save(); } }}注意:我已经测试了dd放入order列中的每一个数据,并且所有数据都获得了真实值。任何想法?
3 回答
梵蒂冈之花
TA贡献1900条经验 获得超5个赞
我认为问题就在这里:
$order->order_data = $cartData;
$cartData
是一个数组,不能直接存入数据库。
这就是为什么出现数组到字符串转换错误的原因。
忽然笑
TA贡献1806条经验 获得超5个赞
我正在寻找相同的解决方案,这对我有用。假设order_dataOrder 模型上的列的类型为 json。Order将模型中的强制转换属性定义order_data为数组。如果您以这种方式使用它,则不需要 json_encode,因为 laravel 会为您将数组转换为 json。
class Order extends Model
{
protected $casts = [
'order_data' => 'array'
];
}
慕虎7371278
TA贡献1802条经验 获得超4个赞
这是因为您尝试将数组作为字符串存储到数据库中,要将数组存储到数据库中,您可以:
$data_to_store=json_encode($array)
然后当回调时$array=json_decode($db_data)
$data_to_store=serialize($array)
然后当回调时$array=unserialize($db_data)
$data_to_store= implode('!!', $array)
然后当回调时$array = explode('!!', $db_data)
- 3 回答
- 0 关注
- 179 浏览
添加回答
举报
0/150
提交
取消