繁体   English   中英

从表到表添加一行

[英]Add one row from table to table

我正在制作宠物应用程序(商店),但我对一件事感到困惑 - 我不明白如何将产品添加到购物车。 我有 2 张桌子 - 产品和购物车,它们有相同的字段。 这是我的代码 Thymeleaf:

<tbody>
            <tr th:each="products : ${products}">
                <td th:text="${products.name}"></td>
                <td th:text="${products.price}"></td>
                <td th:text="${products.quantity}"></td>
                <td th:text="${products.serial}"></td>
                <td>    <p><a href="/product-add" class="btn btn-primary">Add to cart</a></p>
                </td>

            </tr>
            </tbody>

这是我的 controller,应该将一行从产品保存到购物车:

 @RequestMapping("product-add")
    public String addToCart (Model model) {
        model.addAttribute("selection", cartRepository.selection());
        return "redirect:/products";
    }

和查询(我知道它将所有产品复制到购物车,但仅作为示例):

 @Query(value = "insert into cart(select * from products )", nativeQuery = true)
    List<Cart> selection();

我的问题是 - 在这种情况下,我如何只复制一行(一个产品)? 我如何分离产品 ID 以添加到购物车? 应该在 controller 还是在 sql 查询中完成?我只是缺少一些简单的东西((

似乎您的查询正在从带有*符号的产品中选择所有列。 您可以做的是尝试通过在 products 之后使用limit 1来限制查询结果。

此外,如果您想提取具有特定产品 ID 的行,您可以尝试指定条件的简单where关键字。 例如where product_id = your_desired_id它应该返回与您的需求 id 匹配的所有行。

如果您想实际将整个 product_id 列从结果中分离到购物车。 为什么不尝试select [input_here_columns_besides_product_id] from products

祝你好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM