CI 框架多表关联查询

public function getCollectData($limit, $page, $search_user, $search_phone, $orderfield, $ordertype)
    {
        $this->db->select('a.id,a.mobile,a.is_del,a.register_ip,a.add_time,
        b.parent_id as master_id,
        ifnull(inv.award,0) as invite_moneys,
        ifnull(bro.price,0) as brokerage_moneys,
        ifnull(sha.read_price,0) as share_moneys,
        ifnull(sha.counts,0) as share_counts,
        (ifnull(inv.award,0)+ifnull(bro.price,0)+ifnull(sha.read_price,0)) as total_moneys');
        $this->db->from(self::$table_name . ' a');
        $this->db->join('ws_invitation b', 'a.id = b.user_id', 'left');
        $this->db->join('(SELECT sum(award) as award,user_id FROM ws_invitation_log GROUP BY user_id) as inv', 'a.id = inv.user_id', 'left');
        $this->db->join('(SELECT sum(price) as price,prentice_id FROM ws_brokerage_log GROUP BY user_id) as bro', 'a.id = bro.prentice_id', 'left');
        $this->db->join('(SELECT sum(read_number*read_price) as read_price,count(id) as counts,
        user_id FROM ws_share_record GROUP BY user_id) as sha', 'a.id = sha.user_id', 'left');
        $this->db->where(['is_channel' => 0]);

        if ($search_user) {
            $this->db->where(['a.id' => $search_user]);
        }
        if ($search_phone) {
            $this->db->like('a.mobile', $search_phone, 'both');
        }
        if ($orderfield && $ordertype) {
            $this->db->order_by($orderfield . ' ' . $ordertype);
        } else {
            $this->db->order_by('a.id DESC');
        }
        $this->db->group_by('a.id');
        $this->db->limit($limit, $limit * ($page - 1));
        return $this->db->get()->result_array();
    }
原文地址:https://www.cnblogs.com/sgm4231/p/12092805.html