【问题标题】:SQL query using activerecords使用活动记录的 SQL 查询
【发布时间】:2018-05-17 06:43:27
【问题描述】:

我想将下面的 SQL 查询转换为 codeIgniter 活动记录格式

SELECT * FROM `relation`
WHERE (`user1` = 144 OR `user2` = 144)
AND `status` = 2
AND `action` != 1

我的尝试是这样的,

$ID=144;
$this->db->where('user1', $ID);
$this->db->or_where('user2', $ID);
$this->db->where('status', 2);
$this->db->where('action!=', 1);

但是结果不兼容。你能指出这里有什么问题吗?

我也可以接受不专门使用活动记录进行查询的建议。

【问题讨论】:

标签: php codeigniter activerecord codeigniter-3


【解决方案1】:

正确的查询应该是

$query = $this->db
    ->select('*')
    ->from('relation')
    ->group_start()
        ->where('user1', $ID)
        ->or_where('user2', $ID)
    ->group_end()
    ->where('status', 2)
    ->where('action !=', 1)
    ->get();

【讨论】:

    【解决方案2】:

    由于您在多个条件之间使用OR,因此您必须将其括在括号中。更改您的代码如下:

    $this->db->where('(user1', $ID,FALSE);
    $this->db->or_where("user2 = $ID)",NULL,FALSE);
    $this->db->where('status', 2);
    $this->db->where('action!=', 1);
    

    【讨论】:

    • 选择这个作为选择的答案,因为它是一个更灵活和直接的转换。
    【解决方案3】:

    希望对您有所帮助:

    $ID = 144;
    $this->db->select('*');
    $this->db->from('relation');
    $this->db->where('user1', $ID);
    $this->db->or_where('user2', $ID);
    $this->db->where('status', '2');
    $this->db->where('action !=', '1');
    
    $query = $this->db->get();
    if ($query->num_rows() > 0)
    {
      print_r($result);
      //return $query->result();  
    }
    

    更多:https://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-data

    【讨论】:

    • 我在原帖中并不清楚,但我被困在翻译选择逻辑,而不是检索。
    猜你喜欢
    • 2021-06-22
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 2012-11-15
    • 2015-05-10
    • 2016-03-10
    相关资源
    最近更新 更多