![]() |
Active Record Query - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20) +--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23) +--- Thread: Active Record Query (/showthread.php?tid=8559) |
Active Record Query - El Forum - 05-22-2008 [eluser]jamesf[/eluser] Hopefully a quick question, I'm having a problem with a JOIN query. I've got a PROJECTS table which can have multiple ELEMENTS, I've implemented a soft delete approach with a field that is either 'ACTIVE' or 'INACTIVE'. I'm trying to find all the active projects with the count of the active elements Code: $this->db->select('projects.id, projects.name, COUNT(elements.element_type_id) AS num_elements'); If a project has no elements that are active then the project is not returned because of the: Code: $this->db->where("elements.status='ACTIVE'"); Any ideas would be extremely helpful. James Active Record Query - El Forum - 05-22-2008 [eluser]Symcrapico[/eluser] I think that you have to group by "element.project_id" rather than projects.id. If not, post your table schemas so we understand better what your trying to achieve. Active Record Query - El Forum - 05-23-2008 [eluser]jamesf[/eluser] It was just a problem with the WHERE clause on the joined table. Had to hack it a little bit as Active Record doesn't really do sub queries but found a way around this on another thread using: Code: $this->db->ar_from[] = "projects LEFT JOIN (SELECT ... WHERE )"; Active Record Query - El Forum - 05-23-2008 [eluser]Symcrapico[/eluser] Could you post your table schemas with some sample data and the desired results. Unless Im not understanding what you are trying to do, Im pretty sure you dont have to hack AR to get it working. Active Record Query - El Forum - 05-23-2008 [eluser]jamesf[/eluser] Basically in my database a project can have many elements and in my SQL i wanted to find the number of elements for each project that are 'Active'. Code: projects So I needed to implement this SQL in active record which I was under the impression wasn't possible. Code: SELECT projects.*, num_elements I thought you could apply a general where clause on a join table e.g. Code: $this->db->where("elements.status='ACTIVE'"); but if I add this only projects that have active elements are returned which wouldn't be correct. Not to worry too much about it, I've managed to find a solution but thanks for your help. |