向Laravel集合添加新属性

时间:2019-04-08 17:15:30

标签: laravel

我访问了这样的几个收藏

    $articleActions = EloArticleReferenceAction
        ::where('file', '=', $file)
        ->get()
        ->keyBy('type');

    $referencesWithValidDois = EloDoi
        ::where('file', '=', $file)
        ->get();

我想将它们合并。我不能使用merge,因为两个对象中的某些ID相似,因此一个将覆盖另一个。相反,我正在这样做:

    $response = collect();

    foreach ($articleActions as $articleAction) {
        $response->push($articleAction);
    }

    foreach ($referencesWithValidDois as $referencesWithValidDoi) {
        $response->doi->push($referencesWithValidDoi);
    }

但是它在这里中断了。而当我改为执行以下操作时:

    $response = collect();

    foreach ($articleActions as $articleAction) {
        $response->push($articleAction);
    }

    $response['doi'] = [];

    foreach ($referencesWithValidDois as $referencesWithValidDoi) {
        $response['doi'] = $referencesWithValidDoi;
    }

这有点用,但是它会发回这样的对象:

img

其中的doi属性在迭代中被当前的$referencesWithValidDoi覆盖。

因此,目前,它以以下形式发送回:

    0: {...},
    1: {...},
    2: {...},
    3: {...},
    doi: {...}

但是我该怎么写,以便将其发送回:

    0: {...},
    1: {...},
    2: {...},
    3: {...},
    doi: {
        0: {...},
        1: {...},
        2: {...},
        ...
    }

编辑:这样做,

    $response = collect();

    foreach ($articleActions as $articleAction) {
        $response->push($articleAction);
    }

    $response['doi'] = [];

    foreach ($referencesWithValidDois as $referencesWithValidDoi) {
        $response['doi'][] = $referencesWithValidDoi;
    }

引发错误:

Indirect modification of overloaded element of Illuminate\Support\Collection has no effect

3 个答案:

答案 0 :(得分:2)

以下是laravel集合中实现此目的的正确方法,

$response = $articleCollection->put('doi', $referencesWithValidDois);

答案 1 :(得分:0)

您的字体很小,应该是

$response = collect();

foreach ($articleActions as $articleAction) {
    $response->push($articleAction);
}

$response['doi'] = [];

foreach ($referencesWithValidDois as $referencesWithValidDoi) {
    $response['doi'][] = $referencesWithValidDoi;
}

请注意在第二个foreach的response ['doi']之后添加[]。如此有效,您每次都在重写$ reponse ['doi']而不是添加到数组中。

答案 2 :(得分:0)

if(!property_exists($collection, "bar")){
    $collection->bar = collect();
}
$collection->bar->push("some data");
$collection->bar->push("some more data");