简体   繁体   English

stdClass对象的访问变量

[英]Access variable of stdClass Object

I am using Laravel with a select statement to select the row with the highest id like this: 我使用带有选择语句的Laravel选择具有最高ID的行,如下所示:

$user_id = DB::connection('mysql2')->select('SELECT MAX(id) FROM users')[0];

This returns an array with an object that looks like this: 这将返回一个数组,其对象如下所示:

stdClass Object ( [MAX(id)] => 11 ) 1

I have tried $object->MAX(id) and $object['MAX(id)'] but it does not seem to work. 我试过$object->MAX(id)$object['MAX(id)']但它似乎不起作用。

Why are you using the RAW queries when you can utilise the power of Eloquent. 当您可以利用Eloquent的功能时,为什么要使用RAW查询。 You can do this 你可以这样做

User::max('id')

This code will return the maximum value of 'id' column in 'users' table. 此代码将返回“用户”表中“ id”列的最大值。 Given that you have set up your model User . 鉴于您已经设置了模型User You can read more about Eloquent max at given docs link. 您可以在给定的文档链接中阅读有关Eloquent max的更多信息。

可以使用大括号访问通常不允许使用字符的动态属性,如下所示:

$object->{"MAX(id)"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM