我在mysql中有2个表;
items
categories
items
在cat_id
表
categories
列指向其类别
我使用以下查询来获取项目和类别;
SELECT a.id, a.cat_id, a.rest_id, a.name, a.description, a.price, b.rest_id, b.name
FROM items a, categories b
WHERE a.cat_id = b.id AND b.rest_id = 1
我想使用ng-repeat来生成如下所示的列表;
Category A
Item (belongs to cat A)
Item (belongs to cat A)
Item (belongs to cat A)
Category B
Item (belongs to cat B)
Item (belongs to cat B)
Item (belongs to cat B)
如何使用ng-repeat
到目前为止,我有这个但是没有工作;
<div class="results-group" ng-repeat="(key, value) in fetchedData">
<h3 style="text-align: left;"></h3>
<ul>
<li ng-repeat="data in value">
</li>
<ul>
</div>
感谢。
$query1 = "SELECT * FROM categories WHERE rest_id = $restaurant_id";
$select_all_cats = mysqli_query($connection, $query1);
$rows = $select_all_cats -> num_rows;
$arr1 = array();
$arr2 = array();
if($rows > 0) {
while($rows = mysqli_fetch_assoc($select_all_cats)) {
$arr1[] = $rows;
$cat_id = $rows['id'];
$query2 = "SELECT * FROM items WHERE cat_id = $cat_id";
$select_all_items = mysqli_query($connection, $query2);
$rowx = $select_all_items -> num_rows;
if($rowx > 0) {
while($rowx = mysqli_fetch_assoc($select_all_items)) {
$arr2[] = $rowx;
}
}
}
}
答案 0 :(得分:0)
首先,您应该在PHP中删除嵌套查询。循环/嵌套查询是一种反模式,您应该学习识别并通常用适当的查询替换利用连接。
像这样的东西应该在PHP方面起作用:
// array to store results
$item_array = array();
$query = "SELECT
cat.name AS cat_name,
i.id AS id,
i.name AS name,
i.description AS description,
i.price AS price
FROM categories AS cat
INNER JOIN items AS i
ON cat.id = i.id
WHERE i.rest_id = ?
ORDER BY cat_name ASC";
$result = mysqli_query($connection, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
// read into 2D array
$item_array[$row['cat_name']][] = $row;
}
}
重要的是要注意我们在这里构建一个二维数组,类别名称是第一个维度。然后,您可以将此与ng-repeat一起使用,如下所示。请注意,我将在$item_array
上面将itemData
中的数据称为itemData
。另请注意,{j}格式化时,itemData
将采用对象的形式。 <div class="results-group" ng-repeat="(cat, items) in itemData">
<h3 style="text-align: left;">{{cat}}</h3>
<ul>
<li ng-repeat="item in items">
<!-- output content from item here like {{item.name}} and similar -->
</li>
<ul>
</div>
上的每个类别“属性”都将包含项目记录的数字索引数组。
SELECT to_date('36515', 'DDDYY') FROM DUAL