How to use special mysql order_by in codeigniter

Asked

Viewed 131 times

1

in mysql I can do so.

SELECT * FROM `Cidade` ORDER BY `id`=1347 DESC

But I can’t do it in codeigniter, I’m trying it like this:

$this->db->order_by("id = 1347", "DESC")
                ->get("Cidades");

In this case his exit is being so:

SELECT * FROM `Cidade` ORDER BY `id=1347` DESC

he’s putting a bloquote on the whole expression. there’s no funnel. Thanks for helping out.

  • Have you tried it like this: order_by("id", "1347", "DESC")

  • pq has that number? wouldn’t just be the column name?

  • order_by("id", " = 1347 DESC")

  • is the id. It serves to put some more important cities at the top. example, Fortaleza is the capital, but in the natural order it is there by the middle. I’d like her to stay on top, because she’ll be the most used. mysql accepts this type of order_by, but I can’t do it in codeigniter. I have tried this order_by("id", "1347", "DESC"), but it does not roll, I think I will have to write the same sql.

  • 1

    Here it worked exactly as you want it to $c = $this->db->order_by("id = 1347 DESC")->get("City"); var_dump($c->result_array()). You can test it for me and see if it’s anything related to the version?

  • So it did not function. it returned it: SELECT * FROM \City` ORDER BY `id =` 1347 DESC` it puts the = in the bloquote

Show 1 more comment

2 answers

1

The solution I found was writing a sql, not the best way but it worked. if someone has a better way.

return $this->db->query("SELECT * FROM `Cidade` 
                                ORDER BY id = 1347 DESC
                                , id = 1156 DESC
                                , id = 1284 DESC
                                , id = 1337 DESC
                                ");

Thanks!

  • There are some querys that it is better to write this way even, the Active Record of Codeigniter is not prepared for all type, has no problem in doing so.

0

In the last parameter of the method order_by put FALSE, so that the typed text is included without change in what was written, that is, the data will not be escaped, example:

$this->db->order_by("id = 1347", "DESC", FALSE)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.