ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php-在codeigniter中进行查询的优化方式

2019-11-22 17:14:30  阅读:172  来源: 互联网

标签:codeigniter mysql php


我正在Codeigniter中从事一个项目.我在基于多个条件进行查询时遇到问题.最简单的方法是为每个属性设置单独的条件,但是我需要一种优化的方法,因为以后我将拥有25个以上的属性,因此25个条件看起来很奇怪.
这是示例代码

$this->db->select('*');
$this->db->from('listings');
$this->db->join('hotel_features','listings.id = hotel_features.listing_id');
$this->db->where('listings.country_code',$country_t);
$this->db->like('listings.city',$city_t);


    if($room_features_ids != '')
    {
        $room_features_array[0] = "extra_beds";
        $room_features_array[1] = "satellite_tv";
        $room_features_array[2] = "airconditioning";
        $room_features_array[3] = "cable_tv_service";
        $room_features_array[4] = "bathroom";
        $room_features_array[5] = "phone";
        $room_features_array[6] = "wifi";
        $room_features_array[7] = "kitchen";
        $room_features_array[8] = "desk";
        $room_features_array[9] = "refrigerator";   

        $room_features_ids = explode("-",$room_features_ids);

                    // if $room_features_array has 0,1,2 this means first 3 features are available in hotel.
        foreach($room_features_ids as $ids)
        {
            if($room_features_array[$ids] == 'extra_beds')
            {
                $this->db->where('hotel_features.extra_beds',1);    
            }
            else if($room_features_array[$ids] == 'satellite_tv')
            {
                $this->db->where('hotel_features.satellite_tv',1);  
            }
            //and so on.... for all properties
        }
    }

现在我的问题是,有没有优化的方法?
就像是

        foreach($room_features_ids as $ids)
        {
            $this->db->where('hotel_features.'.$room_features_array[$ids],1);   
        }

还是其他方式?提前致谢

解决方法:

具有25个功能,您还将查看25列.如果功能部件的数量经常更改,为什么不使用一对listing_id和功能部件列呢?这样,只需将存在的功能插入数据库即可.

您的WHERE查询可以是

foreach($room_features_ids as $ids)
    {
        $this->db->where('hotel_features.feature', $room_features_array[$ids]);
    }

必须满足所有指定条件的地方.当然,由于您现在要将hotel_features的多个行连接到列表中的单个行,因此您应该汇总hotel_features的行:

$this->db->group_by('listings.id);

标签:codeigniter,mysql,php
来源: https://codeday.me/bug/20191122/2061464.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有