首页 > 解决方案 > 向 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;
    }

它有点工作,但它发回一个像这样的对象:

图像

其中属性在迭代中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

解决方案


以 laravel 集合的方式对此的正确方法如下,

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

推荐阅读