I'm kind of new on codeigniter, hope you can help me.
I have a sql query below, how would it look like on codeigniter framework?
SELECT m.conversation_id, count(m.message_id)
FROM cms_conversations__messages AS m
LEFT JOIN cms_conversations__participants AS p ON p.conversation_id = m.conversation_id AND (p.last_read IS NULL OR m.added > p.last_read) AND m.user_id != 2
WHERE p.user_id = 2
GROUP BY p.user_id
Thank you in advance.
If you are sure that your query is right then this is the codeigniter way to do it
$this->db->select('m.conversation_id, count(m.message_id) as message_count');
$this->db->from('cms_conversations__messages as m');
$this->db->join('cms_conversations__participants as p', 'p.conversation_id = m.conversation_id and (p.last_read IS NULL OR m.added > p.last_read) and m.user_id != 2', 'left');
$this->db->where('p.user_id', '2');
$this->db->group_by('p.user_id');
return $this->db->get()->result(); // or you can also store it in a variable
For more you can see the documention. Hope It helps
As an alternative to using Query Builder you can regular query using query()
which supports bound data. ( Documented Here )
In your case, it could be done like this.
$sql = "SELECT m.conversation_id, count(m.message_id)
FROM cms_conversations__messages AS m
LEFT JOIN cms_conversations__participants AS p ON p.conversation_id = m.conversation_id
AND (p.last_read IS NULL OR m.added > p.last_read)
AND m.user_id != ? WHERE p.user_id = ? GROUP BY p.user_id";
$id = 2;
$query = $this->db->query($sql, [$id, $id]);
//$query might be FALSE, always check for that before trying to get a dataset
if($query !== FALSE)
{
return $query->result();
}
return FALSE;
The data is bound to the two question marks in the $sql
string which gets supplied as the array (ie [$id, $id]
) in the second argument to query()
.
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.