[英]Obtain Array Laravel ->first(); error json_decode() expects parameter
您好,出于某种奇怪的原因,我通过 Laravel 中的数据库查询获得了一个数组,但无法获取该数组
在 ->first(); 获取错误: json_decode() expects parameter 1 to be string, object given
In ->get(); 作品
使用 GET 如果它有效但我只需要第一个
示例: $iduserverified = DB::table('items')->where('id', $request->id)->first();
$decadened = json_decode($iduserverified,true);
$decadened Ahrows:
{#1967 ▼
+"id": 8
+"restaurant_id": 1
+"item_category_id": 1
+"name": "Falso Teleport"
+"price": "321.00"
+"old_price": "0.00"
+"image": "https://i.ytimg.com/an_webp/ifkGKPtSfeo/mqdefault_6s.webp?du=3000&sqp=CPSFhoYG&rs=AOn4CLCIHKSJbZ265w_iWuFUNsnkWJwzfw"
+"is_recommended": 0
+"is_popular": 0
+"is_new": 1
+"created_at": "2021-06-17 18:07:22"
+"updated_at": "2021-06-17 19:00:43"
+"desc": "<p>3</p>"
+"placeholder_image": null
+"is_active": 1
+"is_veg": null
+"order_column": null
+"user_id": "3"
}
用 ->get(); 我没有从 json 解码中得到任何错误,它可以工作,但我只需要获取第一个表 ->first();
用 ->get(); 演员和它的工作原理
Illuminate\Support\Collection {#1761 ▼
#items: array:1 [▼
0 => {#1967 ▼
+"id": 8
+"restaurant_id": 1
+"item_category_id": 1
+"name": "Falso Teleport"
+"price": "321.00"
+"old_price": "0.00"
+"image": "https://i.ytimg.com/an_webp/ifkGKPtSfeo/mqdefault_6s.webp?du=3000&sqp=CPSFhoYG&rs=AOn4CLCIHKSJbZ265w_iWuFUNsnkWJwzfw"
+"is_recommended": 0
+"is_popular": 0
+"is_new": 1
+"created_at": "2021-06-17 18:07:22"
+"updated_at": "2021-06-17 19:00:43"
+"desc": "<p>3</p>"
+"placeholder_image": null
+"is_active": 1
+"is_veg": null
+"order_column": null
+"user_id": "3"
}
]
}
在 Laravel
->get()
根据您的查询返回数据集合。 (集合就像数组,它们包含多个模型实例)
另一方面:
->first()
只返回结果查询的第一行,这意味着结果不是一个数组,而是一个 Model 实例,所以你不需要 json_decode 它,它已经是一个模型,你可以像这样简单地使用它。
$iduserverified = DB::table('items')->where('id', $request->id)->first();
$itemName = $iduserverified->name; // assuming the item model has name.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.