Welcome Guest, Not a member yet? Register   Sign In
Active Record question
#1

[eluser]Bondie[/eluser]
Is there anyway of producing a query with active record to order by id, not by asc or desc, but to provide an order for example; 5,7,3?

SQL would be something along the lines of...
Code:
SELECT  
       id, firstname, lastname, department  
    FROM  
       employees  
    WHERE  
       id IN(5,7,3)  
    ORDER BY  
       FIELD(id,5,7,3);


Edit here's my attempt:
Code:
$comma_separated = implode(",", $this->_get_recently_viewed());
                $get_rece = $this->db->select('id, title, slug, category_id, user_id, price, date_start, date_end, description, images')->
                    from('classifieds_listings')->where_in('id', $this->_get_recently_viewed())->
                    where('date_end >', time())->where('date_start <', time())->order_by('FIELD(`id`, '.$comma_separated.')')->get();

Here's my error:
Quote:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 6

SELECT `id`, `title`, `slug`, `category_id`, `user_id`, `price`, `date_start`, `date_end`, `description`, `images` FROM (`classifieds_listings`) WHERE `id` IN ('7', '3', '2', '6', '1') AND `date_end` > 1327857702 AND `date_start` < 1327857702 ORDER BY FIELD(`id`, `7`, `3`, `2`, `6`, `1)`
the final ` the offending object?
#2

[eluser]vbsaltydog[/eluser]
Can you order that way in SQL without active record?
#3

[eluser]Bondie[/eluser]
Code:
$get_rece = $this->db->query("SELECT `id`, `title`, `slug`, `category_id`, `user_id`, `price`, `date_start`, `date_end`, `description`, `images` FROM (`classifieds_listings`) WHERE `id` IN (".$comma_separated.") AND `date_end` > 1327857702 AND `date_start` < 1327857702 ORDER BY FIELD(`id`, ".$comma_separated.")");

This does the trick, producing:
Quote:SELECT `id`, `title`, `slug`, `category_id`, `user_id`, `price`, `date_start`, `date_end`, `description`, `images` FROM (`classifieds_listings`) WHERE `id` IN (3,7,2,6,1) AND `date_end` > 1327857702 AND `date_start` < 1327857702 ORDER BY FIELD(`id`, 3,7,2,6,1)
#4

[eluser]vbsaltydog[/eluser]
great signature
#5

[eluser]Bondie[/eluser]
Thanks Smile




Theme © iAndrew 2016 - Forum software by © MyBB