将json字符串转换为自定义类的对象,而不是stdClass. [英] Convert json String into Object of custom class instead of stdClass.

查看:72
本文介绍了将json字符串转换为自定义类的对象,而不是stdClass.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 order.php 文件具有

 /**
 * Encode the cart items from json to object
 * @param $value
 * @return mixed
 */
public function getCartItemsAttribute($value){
   return json_decode($value);
}

然后在我的控制器中按以下方式获取cartItems

And in my controller i fetch cartItems as follows

public function orderDetails(Order $order){

   $address = implode(',',array_slice((array)$order->address,2,4));

foreach ($order->cartItems as $item){
    dd($item);
       }
   return view('/admin/pages/productOrders/orderDetails',compact('order','address'));


}

在上面的代码中, dd($ item)将输出如下

And in above code dd($item) will outputs as follows

   {#422 ▼
  +"id": 4
  +"user_id": 2
  +"product_id": 1
  +"quantity": 1
  +"deleted_at": null
  +"created_at": "2018-02-16 08:12:08"
  +"updated_at": "2018-02-16 08:12:08"
}

但是我想要如下.

   Cart {#422 ▼
  +"id": 4
  +"user_id": 2
  +"product_id": 1
  +"quantity": 1
  +"deleted_at": null
  +"created_at": "2018-02-16 08:12:08"
  +"updated_at": "2018-02-16 08:12:08"
}

我如何在laravel中实现这一目标.

How can i achieve this in laravel.

推荐答案

true 作为第二个参数添加到您的解码函数中,例如:

Add true as a second parameter to your decode function like:

/**
 * Decode the cart items from json to an associative array.
 *
 * @param $value
 * @return mixed
 */
public function getCartItemsAttribute($value){
   return json_decode($value, true);
}

我将创建一个 CartItem 模型:

// CartItem.php
class CartItem extends Model {
   public function order() {
        return $this->belongsTo(Order::class);
   }
}

像每个人一样实例化

// Controller.php
$cartItems = [];
foreach ($order->cartItems as $item){
    // using json_encode and json_decode will give you an associative array of attributes for the model.
    $attributes = json_decode(json_encode($item), true);
    $cartItems[] = new CartItem($attributes);

    // alternatively, use Eloquent's create method
    CartItem::create(array_merge($attributes, [
        'order_id' => $order->id
    ]);
}

这篇关于将json字符串转换为自定义类的对象,而不是stdClass.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆