加入活跃记录

时间:2011-09-25 04:16:41

标签: mysql codeigniter activerecord

嗨请求我,我是mysql /活动记录的新手(所有以前的项目都只是基本的CRUD)我正在尝试连接两个表,所以我可以生成一个带小计的发票表(数据库结构)基于竹子发票)

目前正在尝试没有运气(语法错误)

$this->db->select('invoice_number, dateIssued ');
$this->db->select('(SELECT SUM(amount * qty) FROM manage_invoice_items DISTINCT invoice_id) AS subtotal' , FALSE);
$this->db->from('manage_invoices');

$this->db->join('manage_invoice_items', 'manage_invoices.id = manage_invoice_items.invoice_id');
$this->db->where('client_id', $client_id);

$query = $this->db->get();
return $query->result();

$this->db->select('invoice_number, dateIssued');
$this->db->from('manage_invoices');

$this->db->join('manage_invoice_items', 'manage_invoices.id = manage_invoice_items.invoice_id');
$this->db->where('client_id', $client_id);

$query = $this->db->get();

return $query->result();

我得到每个发票项目的结果(我希望每张发票有一个结果,其中包含该发票编号的发票项目小计)

希望所有的发送都像我说的那样我对mysql知之甚少(即使参考一个关于组合函数的好教程也会很方便。

2 个答案:

答案 0 :(得分:2)

我并不熟悉CodeIgniter / ActiveRecord,但看起来你想要的是使用GROUP BY函数对记录进行分组。我发现this link可能会有所帮助。您可能想要使用:

$this->db->select_sum("amount * qty");

$this->db->group_by("invoice_number");                               

答案 1 :(得分:0)

    $this->db->select('invoice_number, dateIssued');
    $this->db->select('ROUND((SUM(amount * qty)), 2) AS subtotal', FALSE);
    $this->db->from('manage_invoices');

    $this->db->join('manage_invoice_items', 'manage_invoices.id = manage_invoice_items.invoice_id');
    $this->db->where('client_id', $client_id);
    $this->db->group_by('invoice_number');
    $query = $this->db->get();


    return $query->result();

感谢Narthring(我不知道group_by