在JOIN表后显示产品名称和产品数量

时间:2017-09-21 09:03:46

标签: php sql codeigniter

这是在Model中查询临时表的功能,我想要两个结果一个产品总数,第二个想要显示每个产品的名称

    public function getProductsName($id){
        CI::db()->select('products.Name, products.id,feedback.feedback_refrence');
        CI::db()->from('products');
        CI::db()->join('feedback', 'products.id = feedback.feedback_refrence');
        CI::db()->where('feedback_refrence', $id);
        CI::db()->where('feedback_status', '1');
        $query = CI::db()->get();
         if ($query->num_rows() > 0) {
        return $query->result();
        } else {
            return false;
        }
    }

这是控制器

    public function index() {
        $data['feedback_name']=\CI::Products()->getProductsName($product->id);
        //load the view
        $this->view('product', $data);
    }
}

这是var_dump结果

    <?php echo ("<pre>"); var_dump($feedback_name); echo ("</pre>");?>
        array(4) {
        [0]=>object(stdClass)#86 (3) {
                ["Name"]=>string(16) "Dawlance 9122MDS"
                ["id"]=> string(2) "24"
                ["feedback_refrence"]=> string(2) "24"
        }
        [1]=>object(stdClass)#87 (3) {
                ["Name"]=>string(16) "Dawlance 9122MDS"
                ["id"]=>string(2) "24"
                ["feedback_refrence"]=>string(2) "24"
        }
        [2]=>object(stdClass)#88 (3) {
                ["Name"]=>string(16) "Dawlance 9122MDS"
                ["id"]=>string(2) "24"
                ["feedback_refrence"]=>string(2) "24"
        }
        [3]=>object(stdClass)#89 (3) {
                ["Name"]=> string(16) "Dawlance 9122MDS"
                ["id"]=>string(2) "24"
                ["feedback_refrence"]=>string(2) "24"
        }
    }

1 个答案:

答案 0 :(得分:1)

尝试为feedback_refrence执行Groupby并选择相同的计数

喜欢:

function getProductsName($id)
    {
    CI::db()->select('products.Name, products.id,feedback.feedback_refrence , COUNT(feedback.feedback_refrence ) as feedback_count');
    CI::db()->from('products');
    CI::db()->join('feedback', 'products.id = feedback.feedback_refrence');
    CI::db()->where('feedback_refrence', $id);
    CI::db()->where('feedback_status', '1');
    CI::db()->group_by('feedback.feedback_refrence');
    $query = CI::db()->get();
    if ($query->num_rows() > 0)
        {
        return $query->result();
        }
      else
        {
        return false;
        }
    }
希望这会有所帮助。