【问题标题】:Convert json String into Object of custom class instead of stdClass.将 json String 转换为自定义类的 Object 而不是 stdClass。
【发布时间】:2025-12-24 05:15:16
【问题描述】:

我的 order.php 文件有

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

在我的控制器中,我按如下方式获取 cartItems

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) 将输出如下

   {#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 中实现这一点。

【问题讨论】:

标签: php laravel laravel-5.5 php-7.1


【解决方案1】:

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

/**
 * 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
    ]);
}

【讨论】:

    最近更新 更多