php - 在 PHP 中加入基于公共 id 的多个集合
问题描述
我有大量具有这种结构的作者:
- authors (id, profile_id, title, name) -> this are 590 authors
我也有 4 个收藏,其中 author.id == author_id
- sales (id, author_id, salesTotal)
- subscribers (id, author_id, subscribersTotal)
- futureEvents (id, author_id, scheduledTotal)
- reservations (id, authors_id, reservationsTotal)
并非所有作者都有销售、订阅者、futureEvents 和/或预订。这些集合没有按任何特定顺序组织。
为了构建作者索引视图,我正在对所有作者进行 FOREACH 循环,因此我需要将所有这五个集合合并为一个,如下所示:
- authors (id, profile_id, title, name, sales, subscribers, futureEvents, reservations)
我怎么能联合所有基于 author_id 的集合,记住每个集合每天都有不同的长度和变化(新作者可以登录、新销售、订阅者登录或退出等)。因此,索引可以每天显示不同的值
知道怎么做吗?
编辑: 我正在使用 LARAVEL,这些集合是每个不同查询的结果。例如:
$authorsSubscribers = DB::table('authors')
->join('subscriptions', 'subscriptions.author_id', '=', 'authors.id')
->groupBy('authors.title')
->selectRaw('authors.id, COUNT(subscriptions.author_id) AS Subscribers')
->get();
结果,我的收藏具有所有相似的结构,例如:
Collection {#86071 ▼
#items: array:5 [▼
0 => {#86015 ▼
+"id": 16
+"Subscribers": 269
}
1 => {#86016 ▼
+"id": 49
+"Subscribers": 269
}
2 => {#86017 ▼
+"id": 20
+"Subscribers": 269
}
3 => {#86018 ▼
+"id": 10
+"Subscribers": 269
}
4 => {#86019 ▼
+"id": 11
+"Subscribers": 269
}
]
}
我不能只做一个大查询,因为我正在分组(GroupBy,计数(COUNT),添加(SUM)等等。
解决方案
我只是添加我找到的解决方案。也许对任何人都有用。
我有trest array:merge、array_map 和array_combine 没有成功。由于数组具有不同的结构、长度和键,因此不可能一对一映射。
所以,我只是使用一个 Foreach 循环来“循环”大集合的每个元素,并使用第二个循环来循环每个元素,比较 author_id 是否相等,如果是,则将其附加为属性。
foreach ($authors as $author ) {
foreach ($sales as $sale) {
if ($author->id === $sale->authorId) {
$author['salesTotal'] = $sale->salesTotal;
$author['salesAmount'] = $sale->salesAmount;
}
}
foreach ($futureEvents as $events) {
if ($author->id === $events->authorId) {
$author['futureEvents'] = $events->futureEvents;
}
}
foreach ($reservations as $reservation) {
if ($author->id === $reservation->authorId) {
$author['reservations'] = $reservation->reservations;
}
}
}
这样我就得到了一个大集合在前端循环。像这样:
Author {#43454 ▼
#attributes: array:14 [▼
"id" => 1
"profile_id" => 4
"title" => "Missourimacejkovic.giles"
... lot of other attributes ...
"created_at" => "2019-02-09 18:49:16"
"updated_at" => "2019-02-09 18:49:16"
"deleted_at" => null
"subscriptions_count" => 2
"events_count" => 19
"salesTotal" => "9086"
"salesAmount" => 200
"futureEvents" => 9
"reservations" => 450
]
}
推荐阅读
- python-3.x - 在创建点的随机列表中创建两点之间的最小距离。在创建我的距离值列表时遇到问题
- vba - 由于单击超链接,是否有以编程方式捕获 PowerPoint 幻灯片窗口失去焦点(停用)的方法?
- python - Sklearn 的 DecisionTreeClassifier 和 CART 的区别
- c# - 无法将 .net core 2.2 添加到 Visual Studio
- sql-server - if 条件确定要创建哪些存储过程
- python - 如何编写查询集以显示链接到某个类别的所有产品?
- python - TypeError:Newton-Raphson 算法中只有大小为 1 的数组错误
- python - 一个 CSV 列中的所有数据,即使我使用数据框将它们拆分或手动设置单独的列
- sql - sql 中列 null 的最新 Effective_start_Date
- c# - Masstransit 中的有序消息