【问题标题】:codeigniter change complex query into active recordcodeigniter 将复杂查询更改为活动记录
【发布时间】:2013-04-11 14:04:30
【问题描述】:

我有一个 codeigniter 应用程序。

我的活动记录语法完美运行,并且是:

  function get_as_09($q){
    $this->db->select('m3');
    $this->db->where('ProductCode', $q);
    $query = $this->db->get('ProductList');
    if($query->num_rows > 0){
        foreach ($query->result_array() as $row){
            $row_set[] = htmlentities(stripslashes($row['m3'])); //build an array
       }
       return $row_set;
    }
  }

这是有效的

select 'm3' from 'ProductList' where ProductCode='$1'

我需要做的是将以下查询转换为活动记录类型查询,并按照上述活动记录语法将其返回给控制器:

select length from
(SELECT  
      [Length]
      ,CONCAT(([width]*1000),([thickness]*1000),REPLACE([ProductCode],concat(([width]*1000),([thickness]*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options
  FROM [dbo].[dbo].[ProductList]) as p
  where options='25100cr' order by length

我想像下面这样,但这不起作用。

$this->db->select(length);
$this->db->from(SELECT  [Length],CONCAT(([width]*1000),([thickness]*1000),REPLACE[ProductCode],concat(([width]*1000),([thickness]*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options
      FROM [dbo].[dbo].[ProductList]);
$this->db->where(options, $q);
$this->db->order(length, desc);

帮助一如既往地感激。再次感谢。

【问题讨论】:

  • 你为什么不直接执行你的 sql 查询呢? $this->db->query($sql)
  • @Brewal,未对注入或任何其他安全漏洞开放?

标签: sql codeigniter activerecord


【解决方案1】:

您可以使用 codeigniter 的子查询方式来实现此目的,您将不得不破解 codeigniter。像这样 转到 system/database/DB_active_rec.php 从这些函数中删除 public 或 protected 关键字

public function _compile_select($select_override = FALSE)
public function _reset_select()

现在可以写入子查询 现在这是您的带有活动记录的查询

$select =   array(
                'Length'
                'CONCAT(([width]*1000)',
                'thickness * 1000',
                'REPLACE(ProductCode, concat((width*1000),(thickness*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options'
);
$this->db->select($select);
$this->db->from('ProductList');

$Subquery = $this->db->_compile_select();

$this->db->_reset_select();

$this->db->select('length');
$this->db->from("($Subquery)");
$this->db->where('options','25100cr');
$this->db->order_by('length');

事情就完成了。干杯!!! 注意:在使用子查询时,您必须使用

$this->db->from('myTable')

而不是

$this->db->get('myTable')

运行查询。

Source

【讨论】:

  • 嗨 raheel,如何设置整个查询 = $q 这样我就可以执行 ` $query=$this->db->query($sql); if($query->num_rows > 0){ foreach ($query->result_array() as $row){ $row_set[] = htmlentities(stripslashes($row['length'])); //建立一个数组 } return $row_set; } }`
  • 而不是 `$query=$this->db->query($sql)` 使用 `$query=$this->db->get()` 而不是你的 if 条件等等上
  • 不管怎样,查询生成器并不是为这样的骇人听闻的事情而设计的。如果您需要子查询等,您应该手动编写查询。您可以使用query bindings 来确保您的数据被转义(也建议事先进行适当的验证)。
猜你喜欢
  • 1970-01-01
  • 2019-01-01
  • 2023-03-24
  • 2016-03-10
  • 2018-07-11
  • 2015-07-17
  • 1970-01-01
相关资源
最近更新 更多