简体   繁体   English

将MySQL查询转换为codeigniter中的活动记录

[英]Converting mysql query to Active record in codeigniter

How do I convert the below to a proper codeigniter active record syntax. 如何将以下内容转换为适当的codeigniter活动记录语法。

function postsInterest($user_id)
{
    $query = $this->db->query("
    SELECT b.*,
    users.country,
    users.company,
    users.pic_small,
    users.subscription,
    COUNT(leads.user_id) AS leads
    FROM trading AS u
    INNER JOIN trading AS b
    LEFT JOIN users ON users.user_id = b.user_id
    LEFT JOIN leads ON b.trade_id = leads.trade_id
    WHERE u.stock_type = b.stock_type
    AND u.buying_selling != b.buying_selling
    AND u.bond = b.bond
    AND u.user_id = $user_id
    AND b.user_id != $user_id
    AND u.timestamp > unix_timestamp(now() - interval 120 DAY)
    AND b.timestamp > unix_timestamp(now() - interval 120 DAY)
    GROUP BY b.trade_id
    ORDER BY b.timestamp DESC");
    if ($query->num_rows() > 0) {
        return $query->result_array();
    } else {
        return false;
    }
}

The above will work for a quick fix but would like to keep it inline with the rest of the queries so I can use the pagination library. 上面的代码可以快速解决问题,但希望使其与其余查询保持一致,以便我可以使用分页库。

I'm not certain that query will work at all. 我不确定该查询是否会正常工作。 INNER JOIN trading AS b but there is no join conditions specified although the required predicates are in the where clause. INNER JOIN trading AS b没有指定 INNER JOIN trading AS b 条件,尽管所需的谓词在where子句中。 These are "join conditions" 这些是“加入条件”

WHERE u.stock_type = b.stock_type
    AND u.buying_selling != b.buying_selling
    AND u.bond = b.bond

In each one of those there is a table u on on side and a table b on the other. 在每一个表中,边上都有一张桌子u ,另一边是一张桌子b When using explicit join syntax you should move all predicates of this sort onto the join. 使用显式联接语法时,应将所有此类谓词移至联接上。

I believe you will have more success converting this to codeigniter syntax: 我相信您将获得更多成功,将其转换为codeigniter语法:

SELECT
      b.*
    , users.country
    , users.company
    , users.pic_small
    , users.subscription
    , COUNT(leads.user_id) AS leads
FROM trading AS u
INNER JOIN trading AS b ON u.stock_type = b.stock_type
      AND u.buying_selling != b.buying_selling
      AND u.bond = b.bond
LEFT JOIN users ON users.user_id = b.user_id
LEFT JOIN leads ON b.trade_id = leads.trade_id
WHERE u.user_id = @user_id
AND b.user_id != @user_id
AND u.timestamp > unix_timestamp(now() - interval 120 DAY)
AND b.timestamp > unix_timestamp(now() - interval 120 DAY)
GROUP BY
      b.trade_id
ORDER BY
      b.timestamp DESC

Please note that you are reliant on MySQL's non-standard support for grouping queries and that if sql_mode changes to only_full_group_by our query would fail. 请注意,您依赖于MySQL对分组查询的非标准支持,并且如果sql_mode由我们的查询更改为only_full_group_将会失败。 At MySQL 5.7.2 the default is only_full_group_by 在MySQL 5.7.2中,默认值为only_full_group_by

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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