如何在Codeigniter中将变量值添加到选择查询结果中?

时间:2019-04-16 10:32:38

标签: sql postgresql codeigniter

我有一个选择查询,它输出几行。查询正在工作,但我需要的是,我想在上面的结果中插入一个带有值的自定义列。 我将Codeigniter 3与PostgreSQL一起使用。查询看起来像

SELECT * FROM tbl_name ORDER BY timestamp ASC LIMIT 6;

我得到的结果是类似的

Array
(
    [0] => Array
        (
            [id] => 1
            [title] => Adventure Honeymoon
            [nights] => 5
            [price] => ₹37,000.00
            [discount] => 0
        )
    [1] => Array
        (
            [id] => 2
            [title] => Wild Side Of Kerala
            [nights] => 4
            [price] => ₹24,000.00
            [discount] => 0
        )
...
)

我想在结果中添加一个名为“ category”的自定义列,其外观应类似于以下内容,

Array
(
    [0] => Array
        (
            [id] => 1
            [title] => Adventure Honeymoon
            [nights] => 5
            [price] => ₹37,000.00
            [discount] => 0
            [category] => Honeymoon Tours                                                                                     
        )
    [1] => Array
        (
            [id] => 2
            [title] => Wild Side Of Kerala
            [nights] => 4
            [price] => ₹24,000.00
            [discount] => 0
            [category] => Wild Life Tours                                                                                     
        )
...
)

我们将为您提供快速帮助。

2 个答案:

答案 0 :(得分:1)

尝试一下

模型

public function get_data(){
   $query = $this->db->select('*')
   ->from('tlb_name')
   ->order_by('timestamp', 'ASC')
   ->limit(6)
   ->get();
   return $query->result_array();  

}

控制器

public function custom_addition(){

   $data = $this->model_name->get_data();

   foreach($data as $row){
       $row['category'] = 'Value';
   }

   print_($data);

}

$data查询结果

答案 1 :(得分:0)

您将使用案例,静态表或联接表根据条件添加列并添加值。 你要改变吗?根据要求更改为值/列名称:

SELECT T1.*, (case when T1.column_name = ? then ? else ? end) as 'CutomColumnName'
FROM TableName T1
ORDER BY T1.timestamp ASC
 LIMIT 6;

例如:

SELECT T1.*, 
   (case when T1.CategoyId=1 then 'Category-1'  
         when T1.CategoyId=2 then 'Category-2'
         else 'Not Found'
    end) as 'CutomColumnName'
    FROM TableName T1
    ORDER BY T1.timestamp ASC
     LIMIT 6;

SELECT T1.*, C1.name 
FROM TableName T1
left outer join category C1 on C1.id=T1.category_id
ORDER BY T1.timestamp ASC
 LIMIT 6;