将SQL查询转换为codeigniter活动记录

时间:2016-01-02 18:43:19

标签: php mysql codeigniter

我正在使用CodeIgniter处理私人消息应用 我有3张桌子:

  1. 会话
  2. conversations_messages
  3. conversations_members。
  4. 我正在尝试通过匹配对话ids来加入表格,并为已登录的用户获取所有消息。

    这是标准的sql查询

        SELECT 
        'conversations','conversation_id',
        'conversations','conversation_subject',
        MAX('conversations_messages','message_date') AS 'conversation_last_reply'
    FROM 'conversations'
    LEFT JOIN 'conversations_messages' ON 'conversations'.'conversation_id' = 'conversations_messages'.'conversation_id'
    INNER JOIN 'conversations_members' ON 'conversations'.'conversation_id' = 'conversations_members'.'conversation_id'
    WHERE 'conversations_members', 'user_id' = $sender_id
    AND 'conversations_members','conversation_deleted' = 0
    GROUP BY 'conversations'.'conversation_id'
    ORDER BY 'conversation_last_reply'  DESC";
    

    这是一个大问题,因此;我不确定如何将其转换为CodeIgniter活动记录,或者只是让它与框架一起运行。

    任何更正也将受到赞赏。

2 个答案:

答案 0 :(得分:0)

使用 CodeIgniter 有效记录尝试以下代码。

 $this->db->select('conversations, conversation_id, conversation_subject');
 $this->db->select_max('conversations_messages.message_date', 'conversation_last_reply');
 $this->db->from('conversations');
 // Joining with conversations_messages table 
 $this->db->join('conversations_messages','conversations.id=conversations_messages.conversation_id','left');
 $this->db->join('conversations_members','conversations.id= conversations_members.conversation_id','inner');
 $this->db->where('conversations_members.user_id',$sender_id);
 $this->db->where('conversations_members.conversation_deleted','0');
 $this->db->group_by('conversations.conversation_id');
 $this->db->order_by('conversation_last_reply');
 // Get the results from db
 $query = $this->db->get();
 // Result array contains the records selected
 $result_array = $query->result_array();

快乐编码

纳西姆

答案 1 :(得分:0)

 $this->db->select('conversations, conversation_id, conversation_subject');
 $this->db->select_max('conversations_messages.message_date', 'conversation_last_reply');
 $this->db->from('conversations');
 // Joining with conversations_messages table 
 $this->db->join('conversations_messages','conversations.id=conversations_messages.conversation_id','left');
 $this->db->join('conversations_members','conversations.id= conversations_members.conversation_id','inner');
 $this->db->where('conversations_members.user_id',$sender_id);
 $this->db->where('conversations_members.conversation_deleted','0');
 $this->db->group_by('conversations.conversation_id');
 $this->db->order_by('conversation_last_reply');
 // Get the results from db
 $query = $this->db->get();
 // Result array contains the records selected
 $result_array = $query->result_array();