【发布时间】:2015-06-25 20:45:11
【问题描述】:
我有一个来自 Laravel Eloquent 查询的集合。这里祖父有很多孩子(父亲),父亲有很多孩子(孙子)。 返回的结果是这样的:
[
{
"grand_father_id": "26",
"fathers": [
{
"father_id": "101",
"children": [
{
"child_id": "77",
"children_weight": [
{
"weight": "30.00",
}
]
},
{
"child_id": "84",
"children_weight": [
{
"weight": "20.00",
}
]
}
]
},
{
"father_id": "102",
"children": [
{
"child_id": "78",
"children_weight": [
{
"weight": "50.00",
}
]
}
]
}
]
},
{
"grand_father_id": "27",
"fathers": [
{
"father_id": "100",
"children": [
{
"child_id": "83",
"children_weight": [
{
"weight": "100.00",
}
]
}
]
}
]
},
{
"grand_father_id": "28",
"fathers": [
{
"father_id": "105",
"children": [
{
"child_id": "81",
"children_weight": [
{
"weight": "80.00",
}
]
},
{
"child_id": "82",
"children_weight": [
{
"weight": "0.00",
}
]
}
]
}
]
},
{
"grand_father_id": "29",
"fathers": [
{
"father_id": "108",
"children": [
{
"child_id": "79",
"children_weight": [
{
"weight": "44.00",
}
]
},
{
"child_id": "80",
"children_weight": [
{
"weight": "56.00",
}
]
}
]
}
]
},
{
"grand_father_id": "30",
"fathers": [
{
"father_id": "107",
"children": [
]
}
]
}
]
我如何计算所有祖父的所有孙子的总数。我当然可以使用嵌套循环来计算这个。但是还有其他 Laravel Collection 方法可以做到这一点吗?顺便说一句,我在这里举的祖父、父亲、孙子的例子只是一个假名的例子。真正的字段是objectives、actions、success_indicators、success_indicator_weight。获取集合的查询是:
return Objective::with([
'actions' => function($query) {
$query->select(['action_id', 'action_description', 'objective_id_fk']);
}, 'actions.successIndicators' => function($query) {
$query->select('success_indicator_id', 'success_indicator_description', 'action_id_fk');
}, 'actions.successIndicators.SuccessIndicatorYearWeight' => function($query) {
$query->select('success_indicator_weight', 'success_indicator_unit', 'success_indicator_id_fk');
},
])->get()
【问题讨论】:
标签: php laravel collections eloquent laravel-5