我正在从我的数据库中提取数据,并希望在每个项目的末尾添加一个对象。以下代码有效,但我假设有一种比重复所有信息并添加到新对象更好的方法。
$cs = $client->contact()->get();
foreach ($cs as $c) {
$contact = (object)[
'id' => $c->id,
'name' => $c->name,
'role' => $c->role,
'phone' => $c->phone,
'address' => $c->address,
'postcode' => $c->postcode,
'otherClients' => Contact::find($c->id)->clients()->get(), //this is the additional info
];
$contacts[]=$contact;
答案 0 :(得分:3)
如果您不需要保持$cs
完整,则可以简单地改变原始对象。
foreach ($cs as $c) {
$c->otherClients = Contact::find($c->id)->clients()->get();
}
答案 1 :(得分:1)
你可以使用
正如@MrCode
所建议的那样$cs = $client->contact()->get();
PHP 5.4 +
foreach ($cs as $c) {
$c->otherClients = Contact::find($c->id)->clients()->get(), //this is the additional info
}
PHP 4或以下
foreach ($cs as &$c) {
$c->otherClients = Contact::find($c->id)->clients()->get(), //this is the additional info
}