如何从 laravel 中的数组中获取键名
How to get keys name from array in laravel
我想获取我的表的列名。当我使用 model::all();
Users::all();
Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => Users Object
(
[table:protected] => users
[hidden:protected] => Array
(
[0] => password
[1] => remember_token
)
[fillable] => Array
(
)
[connection:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[id] => 1
[first_name] => Mohammed Saqib
[last_name] => Rajput
[email] => rajput.saqib@hotmail.com
[dob] => 2015-06-18 00:00:00
[mobile] => 03006710419
[status] => inactive
)
[original:protected] => Array
(
[id] => 1
[first_name] => Mohammed Saqib
[last_name] => Rajput
[email] => rajput.saqib@hotmail.com
[dob] => 2015-06-18 00:00:00
[mobile] => 03006710419
[status] => inactive
)
[relations:protected] => Array
(
)
[visible:protected] => Array
(
)
[appends:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
[dates:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
)
)
)
您可以使用 array_keys
从模型中获取所有属性。
$users = Users::all();
$user = $users->first();
$attributes = array_keys($user->toArray());
或者,您可以使用 this approach 从数据库中的某个 table 获取列名。
现在您可以只使用集合中的 ->keys()
方法。
$fruits = collect(['orange' => 15, 'lemon' => 75]);
$keys = $fruits->keys();
// ['orange', 'lemon']
查看更多
我想获取我的表的列名。当我使用 model::all();
Users::all();
Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => Users Object
(
[table:protected] => users
[hidden:protected] => Array
(
[0] => password
[1] => remember_token
)
[fillable] => Array
(
)
[connection:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[id] => 1
[first_name] => Mohammed Saqib
[last_name] => Rajput
[email] => rajput.saqib@hotmail.com
[dob] => 2015-06-18 00:00:00
[mobile] => 03006710419
[status] => inactive
)
[original:protected] => Array
(
[id] => 1
[first_name] => Mohammed Saqib
[last_name] => Rajput
[email] => rajput.saqib@hotmail.com
[dob] => 2015-06-18 00:00:00
[mobile] => 03006710419
[status] => inactive
)
[relations:protected] => Array
(
)
[visible:protected] => Array
(
)
[appends:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
[dates:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
)
)
)
您可以使用 array_keys
从模型中获取所有属性。
$users = Users::all();
$user = $users->first();
$attributes = array_keys($user->toArray());
或者,您可以使用 this approach 从数据库中的某个 table 获取列名。
现在您可以只使用集合中的 ->keys()
方法。
$fruits = collect(['orange' => 15, 'lemon' => 75]);
$keys = $fruits->keys();
// ['orange', 'lemon']
查看更多