【发布时间】:2020-02-05 15:29:57
【问题描述】:
我有两个表,users 和 like_categories 有 many-to-many 关系。 pivot table 称为 like_category_user。将两个用户数据插入db 后,这是我的pivot table 样子:https://i.imgur.com/MeeRbiV.png
我想为每个 user 计算每个不同的 category 的 amount 并将其存储在 object array 中,如下所示:
[
{
"User Id": 1,
"Like Categories": [
{
"Category": "Chinese Restaurant"
"Amount": 1
},
{
"Category": "Korean Restaurant"
"Amount": 2
},
{
"Category": "Fast Food Restaurant"
"Amount": 3
},
{
"Category": "Italian Restaurant"
"Amount": 1
},
{
"Category": "Steakhouse Restaurant"
"Amount": 3
}
]
},
{
"User Id": 2,
"Like Categories": [
{
"Category": "Thai Restaurant"
"Amount": 1
},
{
"Category": "Kebab Shop"
"Amount": 3
},
{
"Category": "Pizza Place"
"Amount": 2
},
{
"Category": "Steakhouse"
"Amount": 1
}
}
}
]
我尝试将数据库中的数据存储到基于上述格式的对象数组中。但输出不是我想要的。 我的代码:
public function showUserLikesData() {
$users = User::all();
$counter = 0;
$countUser = 0;
$countThatCategory = 0;
$categoryName = '';
foreach($users as $user) {
$userLikesData[$countUser]['User Id'] = $user->id;
foreach ($user->likeCategories as $likeCategory) {
$categoryName = $likeCategory->pivot->category_name;
foreach ($user->likeCategories as $likeCategory) {
$checkCategoryName = $likeCategory->pivot->category_name;
if ($categoryName == $checkCategoryName) {
$countThatCategory++;
}
}
$userLikesData[$countUser]['Like Categories'][$counter]['Category'] = $categoryName;
$userLikesData[$countUser]['Like Categories'][$counter]['Amount'] = $countThatCategory;
$countThatCategory = 0;
$counter++;
}
$countUser++;
$counter=0;
}
return $userLikesData;
}
我得到的object array:
[
{
"User Id": 1,
"Like Categories": [
{
"Category": "Chinese Restaurant",
"Amount": 1
},
{
"Category": "Korean Restaurant",
"Amount": 2
},
{
"Category": "Korean Restaurant",
"Amount": 2
},
{
"Category": "Fast Food Restaurant",
"Amount": 3
},
{
"Category": "Fast Food Restaurant",
"Amount": 3
},
{
"Category": "Fast Food Restaurant",
"Amount": 3
},
{
"Category": "Italian Restaurant",
"Amount": 1
},
{
"Category": "Steakhouse",
"Amount": 3
},
{
"Category": "Steakhouse",
"Amount": 3
},
{
"Category": "Steakhouse",
"Amount": 3
}
]
},
{
"User Id": 2,
"Like Categories": [
{
"Category": "Thai Restaurant",
"Amount": 1
},
{
"Category": "Kebab Shop",
"Amount": 3
},
{
"Category": "Kebab Shop",
"Amount": 3
},
{
"Category": "Kebab Shop",
"Amount": 3
},
{
"Category": "Pizza Place",
"Amount": 2
},
{
"Category": "Pizza Place",
"Amount": 2
},
{
"Category": "Steakhouse",
"Amount": 1
}
]
}
]
【问题讨论】:
-
等等 .. 输出有什么区别?
-
@AntonyMN 有一些冗余密钥。可能是因为我如何循环
-
也许我想问的是......你得到的和你想要的有什么区别?也就是说,解释你真正想做的事情,也许有更简单的方法,或者有一个可用的 laravel 函数
-
@AntonyMN 我编辑了我的帖子 :)
标签: php arrays laravel laravel-5 eloquent