如何在Laravel PHP框架中合并两个集合而不丢失(丢失)键?

时间:2018-07-26 09:00:28

标签: php angularjs laravel

我是Laravel / PHP的新手,我正在做自己的“玩具项目”,遇到了一个我已经使用Google谷歌搜索很长时间的问题。但是,我无法找到完美的解决方案。

问题是,我有两个集合$questions$answers,我想将它们合并为一个大集合。这是这两个集合的结构/示例

$questions

questions: [
{
    id: 1,
    title: "Why do PHP developers love Laravel? What are the things that distinguish Laravel from other PHP frameworks?",
    desc: null,
    user_id: 2,
    created_at: "2018-07-15 06:45:57",
    updated_at: "2018-07-15 06:45:57",
    status: "ok"
}
]

$answers

answers: [
{
    id: 2,
    content: "Laravel is usually considered as PHP on rails! It is amazing!",
    user_id: 2,
    question_id: 1,
    created_at: "2018-07-15 07:11:39",
    updated_at: "2018-07-15 07:11:39"
},
{
    id: 1,
    content: "PHP is the best programming language in the world! [smile]",
    user_id: 1,
    question_id: 1,
    created_at: "2018-07-15 07:02:21",
    updated_at: "2018-07-15 07:05:12"
}
]

我尝试了merge命令,却得到了这样的内容:

$data = $questions->merge($answers);
$data = $data->sortByDesc(function($item) {
    return $item->created_at;
});




data: [
{
    id: 2,
    content: "Laravel is usually considered as PHP on rails! It is amazing!",
    user_id: 2,
    question_id: 1,
    created_at: "2018-07-15 07:11:39",
    updated_at: "2018-07-15 07:11:39"
},
{
    id: 1,
    content: "PHP is the best programming language in the world! [smile]",
    user_id: 1,
    question_id: 1,
    created_at: "2018-07-15 07:02:21",
    updated_at: "2018-07-15 07:05:12"
}
]

注意到,在$data中我再也找不到了问题,但是我确实想在$data集合中找到它。此外,我尝试了unionpushput之类的命令,但没有一个能提供令人满意的解决方案。

我的代码是否有问题,或者我根本无法在PHP中做到这一点?如果我的代码中有错误,请粘贴到这里。

public function timeline()
{
    list($limit, $skip) = paginate(rq('page'), rq('limit'));

    /* Retrieve questions, $questions is like I pasted above*/
    $questions = question_init()
        ->limit($limit)
        ->skip($skip)
        ->orderBy('created_at', 'desc')
        ->get();

    /* Retrieve answers, $answers is like I pasted above */
    $answers = answer_init()
        ->limit($limit)
        ->skip($skip)
        ->orderBy('created_at', 'desc')
        ->get();        

    /* Merge questions and answers */
    $data = $questions->merge($answers);

    /* Sort by Created time */
    $data = $data->sortByDesc(function($item) {
        return $item->created_at;
    });

    $data = $data->values()->all();

    return succ(['questions' => $questions, 'answers' => $answers, 'data' => $data]);
}

2 个答案:

答案 0 :(得分:6)

这是因为扩展支持集合的Eloquent集合使用的词典是由合并时所包含的Model实例的键来键入的。它们具有专门用于处理模型集合的特殊功能。通常,因此您不会像这样合并Eloquent Collections。

您可以从一个口才集合中获得支持集合,然后将另一个集合合并到其中。

$collection->toBase()会给您Illuminate\Support\Collection中的Illuminate\Database\Eloquent\Collection

您可以尝试:

$data = $questions->toBase()->merge($answers);

答案 1 :(得分:1)

使用可以使用:

修改

$merged = array_merge(['questions' => $questions], ['answers' => $answers])

它将返回与每个集合的正确键合并的数组。