简体   繁体   中英

Converting mysql query to Active record in codeigniter

How do I convert the below to a proper codeigniter active record syntax.

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. 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. 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:

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. At MySQL 5.7.2 the default is only_full_group_by

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.

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