我已经在一个SQL查询中编写了它并且工作正常。我如何在 codeigniter 中写这个?
$sql = "SELECT *
FROM single_message
WHERE
( school_id='$schoolId' AND
classId='$classId' AND
sectionId='$sectionId' AND
sender_id='$senderId' AND
receiver_id ='$receiverId'
) OR
( chool_id='$schoolId' AND
classId='$classId' AND
sectionId='$sectionId' AND
sender_id='$receiverId' AND
receiver_id ='$senderId'
)
ORDER BY messageId DESC"`;
这是我尝试过的:
$condition = array(
'school_id' => $schoolId,
'classId' => $classId,
'sectionId' => $sectionId,
'sender_id' => $senderId,
'receiver_id' => $receiverId
);
$this->db->select('*');
$this->db->where($condition);
return $this->db->get('single_message')->result_array();
答案 0 :(得分:1)
根据您的SQL查询:
$sql = "SELECT * FROM single_message WHERE (school_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$senderId' AND receiver_id ='$receiverId') OR (chool_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$receiverId' AND receiver_id ='$senderId') ORDER BY messageId DESC";
有两种方法可以编写查询。我将逐一解释:
解决方案1: 您可以简单地将条件放在where子句中,如下所述 - >
$condition = "(school_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$senderId' AND receiver_id ='$receiverId') OR (chool_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$receiverId' AND receiver_id ='$senderId')";
$this->db->select('*');
$this->db->where($condition);
return $this->db->get('single_message')->result_array();
在这里你可以看到我已经完成了以字符串格式传递条件的地方。这是fisrt解决方案。编写此查询的另一种方法是。
解决方案第二: 查询分组 - >它允许您通过将它们括在括号中来创建WHERE子句组。所以查询就像:
$condition['AND'] = array(
'school_id' => $schoolId,
'classId' => $classId,
'sectionId' => $sectionId,
'sender_id' => $senderId,
'receiver_id' => $receiverId
);
$condition['OR'] = array(
'school_id' => $schoolId,
'classId' => $classId,
'sectionId' => $sectionId,
'sender_id' => $receiverId,
'receiver_id' => $senderId
);
$this->db->select('*');
// Starts first group
$this->db->group_start();
// AND condition placed in below line
$this->db->where($condition['AND']);
// First group ends here
$this->db->group_end();
// Another group has been started here for OR clause
$this->db->or_group_start();
// Here we placed our OR codition
$this->db->where($condition['OR']);
// Second group ends here
$this->db->group_end();
return $this->db->get('single_message')->result_array();
它将产生您需要的确切结果。如果您有任何疑问,请告诉我。有关更多详细信息,请在此处阅读查询生成器说明:Query Grouping
答案 1 :(得分:0)
将第二个参数作为null
传递,将第三个参数作为false
传递将无法转发您的查询。
试用此代码:
$this->db->select('*');
$this->db->where("school_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$senderId' AND receiver_id ='$receiverId') OR (chool_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$receiverId' AND receiver_id ='$senderId'", null, false);
$this->db->order_by("messageId", "desc");
$this->db->get();
以下是codeigniter文档中的Where reference。