我有一个带有类别列的技能表。我想从表中获取所有结果,遍历各个类别并按表格过滤每个类别的结果。
要做到这一点,我想我会使用Laravel的集合方法。麻烦的是,我没有得到一致的结果。
我写这篇文章来比较不同的输出:
$skills = Skill::all();
$frameworks = $skills->where('category', 'Frameworks');
$backend = $skills->where('category', 'Backend');
return [
'db_backend' => Skill::where('category', 'Backend')->get(),
'collection_backend' => $backend,
'db_frameworks' => Skill::where('category', 'Frameworks')->get(),
'collection_frameworks' => $frameworks
];
这给了我以下输出:
{
"db_backend": [
{
"id": 1,
"created_at": "2017-11-20 02:39:20",
"updated_at": "2017-11-20 02:39:20",
"name": "PHP",
"notes": "",
"category": "Backend"
}
],
"collection_backend": [
{
"id": 1,
"created_at": "2017-11-20 02:39:20",
"updated_at": "2017-11-20 02:39:20",
"name": "PHP",
"notes": "",
"category": "Backend"
}
],
"db_frameworks": [
{
"id": 2,
"created_at": "2017-11-20 02:39:20",
"updated_at": "2017-11-20 02:39:20",
"name": "Wordpress",
"notes": "",
"category": "Frameworks"
}
],
"collection_frameworks": {
"1": {
"id": 2,
"created_at": "2017-11-20 02:39:20",
"updated_at": "2017-11-20 02:39:20",
"name": "Wordpress",
"notes": "",
"category": "Frameworks"
}
}
}
因此,作为Eloquent查询的where方法提供了一致的输出。但是收集的where方法似乎是添加了一个额外的密钥,但在两种情况下都没有。我唯一能看到的就是“PHP”技能的不同之处在于它是第一次进入该表,但我不明白为什么会导致这种行为。
我做错了什么还是这个错误?