简体   繁体   中英

Access variable of stdClass Object

I am using Laravel with a select statement to select the row with the highest id like this:

$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.

Why are you using the RAW queries when you can utilise the power of Eloquent. You can do this

User::max('id')

This code will return the maximum value of 'id' column in 'users' table. Given that you have set up your model User . You can read more about Eloquent max at given docs link.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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