在选择查询表名称上使用变量

时间:2016-02-05 11:55:08

标签: mysql codeigniter-3

我需要在模型选择查询上使用动态表名,如下所示:

$this->db->select("$this->table_car.id as carId, $this->table_car.price as carPrice, $this->table_car.name as carName, $this->table_car.used as carUsed, $this->table_car.visible as carVisible, $this->table_cat.name as catName, $this->table_brand.name as carBrand, $this->table_model.name as carModel");

但变量不起作用。这就是我得到的:

SELECT .`id` AS `carId`, .`price` AS `carPrice`, .`name` AS `carName`, .`used` AS `carUsed`, .`visible` AS `carVisible`, .`name` AS `catName`, .`name` AS `carBrand`, .`name` AS `carModel`
LEFT JOIN ON .`car_id` = .`id`
LEFT JOIN ON .`id` = .`cat_id`
LEFT JOIN ON .`id` = .`brand_model_id`
LEFT JOIN ON .`id` = .`model_id`
LEFT JOIN ON .`id` = .`brand_id`
WHERE .`used`= 0 LIMIT 3

有解决方法吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

虽然双引号允许在其中使用变量而不需要关闭和连接,但它并不总是适用于喜欢或对象和数组,就像你正在展示的那样。更好的解决方案是:

$this->db->select($this->table_car . ".id as carId, " 
    . $this->table_car . ".price as carPrice, " 
    . $this->table_car . ".name as carName, " 
    . $this->table_car . ".used as carUsed, " 
    . $this->table_car . ".visible as carVisible, " 
    . $this->table_cat . ".name as catName, " 
    . $this->table_brand . ".name as carBrand, " 
    . $this->table_model . ".name as carModel");

另一种选择是将对象变量放在大括号{}中,例如:

$this->db->select("{$this->table_car}.id as carId, 
    {$this->table_car}.price as carPrice, 
    {$this->table_car}.name as carName, 
    {$this->table_car}.used as carUsed, 
    {$this->table_car}.visible as carVisible, 
    {$this->table_cat}.name as catName, 
    {$this->table_brand}.name as carBrand, 
    {$this->table_model}.name as carModel");