[英]Laravel - Accessing, Manipulate and Looping Through Pivot Table
我有兩個表, 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
}
}
}
]
我試圖將數據庫中的數據存儲到基於上述格式的 object 數組中。 但是 output 並不是我想要的樣子。 我的代碼:
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
}
]
}
]
如果您需要相同的 output 只需更換這個
$users = User::all();
至
$users = User::all()->toArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.