我目前遇到了 laravel 的问题,其中 Illuminate\Database\Eloquent\Collection 始终作为对象而不是数组返回 - 导致我的 vue 组件出现问题。
Route::get('/users', function (Request $request) {
$users = User::all();
$filtered = $users->filter( function ($user) {
if($user->can('viewAny', 'App\Module')){
return true;
}
});
return $filtered;
}
Run Code Online (Sandbox Code Playgroud)
通过过滤器的任何内容都拒绝隐式或显式转换为数组:
return User::all(); //Returns Array
return $filtered; //Returns object
return $filtered->toArray(); //Returns object?!
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?Laravel 版本是 5.8,$filtered 中的典型 User 对象如下所示:
3: {
id: 4,
first_name: "Alexandrea",
last_name: "Lind",
email: "russel.oda@example.net",
email_verified_at: "2019-09-25 20:35:03",
created_at: "2019-09-25 20:35:03",
updated_at: "2019-09-25 20:35:03",
is_admin: false,
cycle: 2019,
widening_access_pricing: 0,
can_comment: 1,
can_comment_without_approval: 0,
email_consent: "2019-09-25 20:35:03",
affiliate_id: null,
purchases: [
{
id: 28,
payment_intent_id: "pi_1FoAWUAsJiXFAGV72unvUP6a",
status: "succeeded",
user_id: 4,
product: null,
module_id: 6,
created_at: "2019-12-10 15:21:14",
updated_at: "2019-12-10 15:21:16"
}
],
completion_records: [
]
},
Run Code Online (Sandbox Code Playgroud)
如果您不需要由记录的“id”键控的数据,您可以调用valuesCollection 来重置键:
return $filtered->values();
Run Code Online (Sandbox Code Playgroud)
JSON 无法将关联数组表示为数组,它必须将其表示为对象。零索引数组可以表示为 JSON 中的数组,因为它的键是连续的,因此不需要以任何特殊方式表示。
Laravel 6.x 文档 - 集合 - 可用方法 -values
| 归档时间: |
|
| 查看次数: |
1047 次 |
| 最近记录: |