已从数据库中检索了模型及其必要关系(急切加载)的集合。在进一步处理结果时,有必要将某些关系逆转。为了节省资源,不应从数据库中加载其他关系。
初始查询如下:
$resource = Model_A::with([
'Model_B',
'Model_C'
])->paginate(25);
初始结果如下:
Collection {
#items: array:3 [
0 => Model_A {
...
#relations: array:2 [
"Relation_Model_B" => Model_B { ... },
"Relation_Model_C" => Model_C { ... }
...
},
1 => Model_A {
...
#relations: array:2 [
"Relation_Model_B" => Model_B { ... },
"Relation_Model_C" => Model_C { ... }
...
},
2 => Model_A {
...
#relations: array:2 [
"Relation_Model_B" => Model_B { ... },
"Relation_Model_C" => Model_C { ... }
...
}
]
};
转换后,结果应如下所示:
Collection {
#items: array:2 [
0 => Model_B {
...
#relations: array:1 [
"Relation_Model_A" => array:3 [
0 => Model_A { ... },
1 => Model_A { ... },
1 => Model_A { ... }
]
]
...
},
1 => Model_C {
...
#relations: array:1 [
"Relation_Model_A" => array:3 [
0 => Model_A { ... },
1 => Model_A { ... },
1 => Model_A { ... }
]
]
...
}
]
};
我已经研究过Illuminate\Database\Eloquent\Builder
和Illuminate\Database\Eloquent\Model
类,但是我对PHP和Laravel的了解还不足以独自解决。
感谢您的支持!非常感谢!