将新属性添加到Laravel集合

问题描述 投票:1回答:2

我访问了几个像这样的集合,

    $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

laravel
2个回答
2
投票

laravel集合的正确方法如下,

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

0
投票

你应该是一个小型的

$response = collect();

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

$response['doi'] = [];

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

注意在第二个foreach中响应['doi']后添加[]。所以你每次都有效地重写$ reponse ['doi'],而不是添加到数组中。

© www.soinside.com 2019 - 2024. All rights reserved.