【问题标题】:ng-repeat grouping with mysql使用 mysql 进行 ng-repeat 分组
【发布时间】:2015-11-05 19:28:21
【问题描述】:

我在 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;
            }
        }
    }
}

【问题讨论】:

  • 您可以使用 2 个查询来处理此问题,一个用于循环查找类别,另一个用于查找项目
  • 我如何实现我想要的列表?

标签: php mysql angularjs angularjs-ng-repeat ng-repeat


【解决方案1】:

首先,您应该删除 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,在为 javascript 格式化时将采用对象的形式。 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>

【讨论】:

    猜你喜欢
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多