Karina
Karina

Reputation: 661

Order by variable in Kohana

I know this is a silly question but I would like to know how to correctly add a variable to order by using Kohana, so far I have the following query where I have added the variable I want to the where clause, this works fine but when I apply the same for the order_by it doesn't work, do I have to specify it in a different way? I just need to order by the variables as these will be dynamically populated.

$geoquery = DB::select('store_id', 'city')
            ->from('mytable')
            ->where('latitude', '>=', $latitude * .9)
            ->and_where('longitude', '<=', $longitude * 1.1)
            ->order_by('ABS(`latitude` - 51.507202) + ABS(`longitude` - -0.223242))')
            ->limit(1)
            ->execute('mytable');

Upvotes: 0

Views: 84

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

I guess you need to use Database Expressions for your order_by

$geoquery = DB::select('store_id', 'city')
            ->from('mytable')
            ->where('latitude', '>=', $latitude * .9)
            ->and_where('longitude', '<=', $longitude * 1.1)
            ->order_by(DB::Expr('ABS(`latitude` - 51.507202) + ABS(`longitude` - -0.223242))'))
            ->limit(1)
            ->execute('mytable');

According to docs

There are cases were you need a complex expression or other database functions, which you don't want the Query Builder to try and escape. In these cases, you will need to use a database expression created with DB::expr. A database expression is taken as direct input and no escaping is performed

Upvotes: 1

Related Questions