问题描述
您好,出于某种奇怪的原因,我通过 Laravel 中的数据库查询获得了一个数组,但无法获取该数组
在 ->first();获取错误:json_decode() expects parameter 1 to be string,object given
在 ->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()
只返回结果查询的第一行,这意味着结果不是一个数组,而是一个模型实例,所以你不需要json_decode它,它已经是一个模型,你可以像这样简单地使用它.
$iduserverified = DB::table('items')->where('id',$request->id)->first();
$itemName = $iduserverified->name; // assuming the item model has name.