简体   繁体   中英

If condition in mySQL query with join in Codeigniter

Good Day!

Is it possible to apply if condition in the query in codeigniter: model ? I have this query in Model :

function activity($id) {        
        $this->db->select('a.ID, a.activityID, r.roleName');
        $this->db->from('activity a');
        $this->db->join('role r', 'r.ID = a.activityID');
        $this->db->where('a.ID', $id);
        $query = $this->db->get();

        return $query->result_array();
    }

And in my view I want to show the ID and activityID from table activity and also the counter part roleName (from table role) of activityID . But the tricky part is that the value in activityID is not just a simple INT , like this:

ID  ActivityID
1   5,7,9
2   2,4
3   
4   10
5   1,6

So I'm thinking to use if condition in the query, like if the activityID value not contains comma (,) it will use join like this: $this->db->join('role r', 'r.ID = a.activityID'); then get the r.roleName . Example:

ID  ActivityID  Role Name
4   10          Basketball

But if contains comma (,), it will explode by comma (,) then join like this: $this->db->join('role r', 'r.ID = a.activityID'); but it will output also by roleName with comma in between. Example:

ID  ActivityID  Role Name
1   5,7,9       Tennis,Football,Soccer
2   2,4         Volleyball,Chess

Can someone help me with this? Thanks in advance.

This is very bad idea to have comma separated ids in your column you should first normalize your structure other wise it will lead you more expensive problems,for now you use FIND_IN_SET() ,for having role names also as comma separated you can use GROUP_CONCAT

Be ware of that fact it has a default limit of 1024 characters to concat but it can be increased which is defined in manual

SELECT 
a.ID, 
GROUP_CONCAT(a.activityID) activityID,
GROUP_CONCAT(r.roleName) roleName
  FROM activity a
  LEFT JOIN `role` r ON(FIND_IN_SET(r.ID,a.activityID) > 0);
  WHERE a.ID = $id
  GROUP BY a.ID

For CI use query() function for above query

Please first have a look at Database Normalization

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM