gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:55:29 26 4
gpt4 key购买 nike

我是 Laravel/PHP 的新手,我正在做我的个人“玩具项目”,我遇到了一个我在谷歌上搜索了很长时间的问题。但是,我想不出一个完美的解决方案。

问题是,我有两个集合 $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 中找到它收藏。此外,我尝试过类似 union 的命令。 , push , put ,他们都没有给出令人满意的解决方案。

我的代码有问题还是我根本无法在 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]);
}

最佳答案

这是因为扩展支持集合的 Eloquent 集合使用一个字典,该字典由合并时包含的模型实例的键作为键。它们具有专门用于处理模型集合的特殊功能。通常你不会因为这个原因合并像这样的 Eloquent Collections。

您可以从 Eloquent 集合之一中获取支持集合并将另一个集合合并到其中。
$collection->toBase()会给你一个Illuminate\Support\Collection来自您的 Illuminate\Database\Eloquent\Collection .

你可以试试:

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

关于php - 如何在 Laravel PHP 框架中合并两个集合而不删除(丢失)键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51534929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com