【问题标题】:Fetch featured product only from product table in Api仅从 Api 中的产品表中获取特色产品
【发布时间】:2021-08-05 12:13:03
【问题描述】:

产品表

我只想获取特色产品。我在数据库 product_type 中定义了一个列,其中可以列出四种类型的产品(热卖、新上市、当日特价和特色产品)强文本,这是可选的。

块引用

   Here is my model|query code in codeigniter
    

 public function featured_product()
 {
    $arrResult = array();
    
    $this->db->select('*');
    $this->db->from('product');
    $this->db->where("product_type","featured");
    $result = $this->db->get()->result_array();
    if(!empty($result))
    {
        $arrResult['result'] = $result;
    }
    else
    {
        $arrResult['result'] = '';
    }
    return $arrResult ;
  }

当我尝试在 api 中获取整个产品列表时,我得到了结果,但我只想显示特色产品。

【问题讨论】:

  • 如果为时不晚,请更改数据库设计,以免在数据库列中使用逗号分隔列表。 stackoverflow.com/questions/3653462/…
  • 嘿@RiggsFolly 感谢您的建议,我的意思是修改数据库,但对于知识前景,我们可以使用我上面定义的方式。我的代码在这里错了吗?如果我的代码错了,应该用这种方式解决什么问题。

标签: php mysql api codeigniter


【解决方案1】:

你可以尝试使用find_in_set:

https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_find-in-set

我不知道 codeigniter,但我认为,这看起来很有用:

https://forum.codeigniter.com/thread-71337.html

【讨论】:

  • 嘿@akrys 你的帖子帮助我完成了我不知道的 FIND_IN_SET() 函数,它在我的代码中可以正常工作
【解决方案2】:

我提出了一种不同的方法。

这不是您问题的答案,但我希望它能让您重新考虑您的表结构。

不要将所有product_types 存储在单个列中,而是使用pivot table(也称为联结表)。

您需要将当前在product_types 列中的所有数据存储在一个单独的表中(枢轴,我们称之为product_to_type)并引用product_tableproduct_typeid在数据透视表中。

类似这样的:

这里有一个不错的db-fiddle,如果你愿意的话,可以玩一下。

这有很多好处:

  • 你有一个atomic tables
  • 您可以向任一表添加数据,而不会在其他表中造成问题
  • 外键确保数据一致性(您可能会做得更好。使用的键不错但不是很好)
  • 您可以通过正确使用连接来提取任何类型的数据
  • 您可以添加索引以使查询更流畅

我相信还有其他优势。

【讨论】:

  • 谢谢@Andrei,我已经用单独的表格完成了。
【解决方案3】:
 As i have changed my database to separate table with product_id matching with product_type. Still i find the solution to my question with a function FIND_IN_SET(). Here is my updated modal query 

  public function featured_product()
{
    $arrResponse = array();
    $data = 'featured';
    $this->db->select('*');
    $this->db->where('find_in_set("'.$data.'", product_type) <> 0');
    $this->db->from('product');
    $result = $this->db->get()->result_array();
    if(!empty($result))
    {
        $arrResponse['result'] = $result;
    }
    else
    {
        $arrResponse['result'] = '';
    }
    return $arrResponse ;
 }

顺便谢谢大家

【讨论】:

    猜你喜欢
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多