尝试从结果中选择值时尝试获取非对象的属性

我的功能有问题。我请求从数据库中选择,选择是正常的,并且有第二个代码应该price从结果中获取列的值,但问题是我得到一个错误结果:Trying to get property of non-object.

我的代码:

$betitem = \DB::table('items')->where('status', 0)->where('price', '>=', 10)->orderByRaw('RAND()')->take(1)->get();
$green_tickets = $betitem->price;

如果写var_dump($betitem[0]); exit;我收到:

object(stdClass)#584 (13) { ["id"]=> int(548) ["assetid"]=> string(11) "18235855849" ["market_hash_name"]=> string(15) "Staff of Gun-Yu" ["classid"]=> string(231) "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KW1Zwwo4NUX4oFJZEHLbXK9QlSPcU_phVWSVXvTO2j0IDeXFN_IB1ovbOrLDhp3v7HYylD4OOhkYGbmPm7PrTfnW5I1854hO7-_IH4h0agqh8DJDyiZNnLbAE8M13Q-Ae4wrq7g5Pq7cufnCRm7nZ3tCyPlhSyhx1IabZrjPKaQVqAR_se2_6rU3g" ["price"]=> float(26.4) ["steamid"]=> string(1) "1" ["type"]=> string(4) "card" ["bot"]=> string(1) "1" ["status"]=> int(0) ["created_at"]=> string(19) "2020-02-27 01:47:12" ["updated_at"]=> string(19) "2020-03-14 17:41:25" ["is_withdraw"]=> int(0) ["is_raffling"]=> int(0) }

我如何理解问题的出现是因为结果是在数组中接收的。但是如何修复这个错误并从price列中获取结果呢?


jeck猫
浏览 105回答 3
3回答

千万里不及你

由于$betitem数组中有一个对象,您可以这样做$green_tickets = $betitem[0]->price;或者您可以使用该first()方法获取与您的条件匹配的第一行。$betitem = \DB::table('items')->where('status', 0)->where('price', '>=', 10)->orderByRaw('RAND()')->take(1)->first(); $green_tickets = $betitem->price;另外,我可以看到一个额外的\before DB。您可以use DB;在声明类之前添加它应该可以正常运行。确保此DB别名存在于您的config/ app.php.

慕的地8271018

在这种情况下,使用 first() 而不是 take(1)->get()$betitem = \DB::table('items')->where('status', 0)->where('price', '>=', 10)->orderByRaw('RAND()')->first(); $green_tickets = $betitem->price;

holdtom

尝试这个$betitem  = items::where('status',0)->andWhere('price', '>=', 10)->orderBy('id', 'ASC')->take(1)->get(); $green_tickets = $betitem->price;
打开App,查看更多内容
随时随地看视频慕课网APP