DB query - how to order by absolute values? - php

I have query that fetch data...
I want to order it by absolute value,
current query:
$someVar = DB::table('tblName')->where('id', $id)->orderBy('size', 'desc')->get
I tried to do something like orderBy(Abs('size'), 'desc')->get
but it didn't work and can't find any solution in the documentations.
Anyone know the solution?

You need to use the method raw for this to work.
->orderBy(DB::raw('ABS(size)'), 'desc');

Related

Laravel: like won't work for some reason

Why this query is not working. Executing same thing in sql database returns me this one result that's in image. so doing q select * from kolejka where data like '2017-04-08%' in mysql works. In php artisan tinker it won't work and I cannot figure out why.
When you're using all() first, you get all data and then work with it. like won't work here. So, do this instead:
\App\Kolejka::where('data', 'like', '2017-04-08%')->get();
If you just want to get records by date, just use whereDate():
\App\Kolejka::whereDate('data', Carbon\Carbon::parse('2017-04-08'))->get();

Laravel: How to get last N entries from DB

I have table of dogs in my DB and I want to retrieve N latest added dogs.
Only way that I found is something like this:
Dogs:all()->where(time, <=, another_time);
Is there another way how to do it? For example something like this Dogs:latest(5);
Thank you very much for any help :)
You may try something like this:
$dogs = Dogs::orderBy('id', 'desc')->take(5)->get();
Use orderBy with Descending order and take the first n numbers of records.
Update (Since the latest method has been added):
$dogs = Dogs::latest()->take(5)->get();
My solution for cleanliness is:
Dogs::latest()->take(5)->get();
It's the same as other answers, just with using built-in methods to handle common practices.
Dogs::orderBy('created_at','desc')->take(5)->get();
You can pass a negative integer n to take the last n elements.
Dogs::all()->take(-5)
This is good because you don't use orderBy which is bad when you have a big table.
You may also try like this:
$recentPost = Article::orderBy('id', 'desc')->limit(5)->get();
It's working fine for me in Laravel 5.6
I use it this way, as I find it cleaner:
$covidUpdate = COVIDUpdate::latest()->take(25)->get();
Ive come up with a solution that helps me achieve the same result using the array_slice() method. In my code I did array_slice( PickupResults::where('playerID', $this->getPlayerID())->get()->toArray(), -5 ); with -5 I wanted the last 5 results of the query.
The Alpha's solution is very elegant, however sometimes you need to re-sort (ascending order) the results in the database using SQL (to avoid in-memory sorting at the collection level), and an SQL subquery is a good way to achieve this.
It would be nice if Laravel was smart enough to recognise we want to create a subquery if we use the following ideal code...
$dogs = Dogs::orderByDesc('id')->take(5)->orderBy('id')->get();
...but this gets compiled to a single SQL query with conflicting ORDER BY clauses instead of the subquery that is required in this situation.
Creating a subquery in Laravel is unfortunately not simply as easy as the following pseudo-code that would be really nice to use...
$dogs = DB::subQuery(
Dogs::orderByDesc('id')->take(5)
)->orderBy('id');
...but the same result can be achieved using the following code:
$dogs = DB::table('id')->select('*')->fromSub(
Dogs::orderByDesc('id')->take(5)->toBase(),
'sq'
)->orderBy('id');
This generates the required SELECT * FROM (...) AS sq ... sql subquery construct, and the code is reasonably clean in terms of readability.)
Take particular note of the use of the ->toBase() function - which is required because fromSub() doesn't like to work with Eloquent model Eloquent\Builder instances, but seems to require a Query\Builder instance). (See: https://github.com/laravel/framework/issues/35631)
I hope this helps someone else, since I just spent a couple of hours researching how to achieve this myself. (I had a complex SQL query builder expression that needed to be limited to the last few rows in certain situations).
For getting last entry from DB
$variable= Model::orderBy('id', 'DESC')->limit(1)->get();
Imagine a situation where you want to get the latest record of data from the request header that was just inserted into the database:
$noOfFilesUploaded = count( $request->pic );// e.g 4
$model = new Model;
$model->latest()->take($noOfFilesUploaded);
This way your take() helper function gets the number of array data that was just sent via the request.
You can get only ids like so:
$model->latest()->take($noOfFilesUploaded)->puck('id')
use DB;
$dogs = DB::select(DB::raw("SELECT * FROM (SELECT * FROM dogs ORDER BY id DESC LIMIT 10) Var1 ORDER BY id ASC"));
Dogs::latest()->take(1)->first();
this code return the latest record in the collection
Can use this latest():
$dogs = Dogs::latest()->take(5)->get();

how can i use multiple where clause In codeigniter?

For my database query I have to use multiple where clause query in Codeigniter PHP. I wrote the code like this:
$this->db->and_where_in('category_name,publication_status','home_headline_sub',1);
But this query shows database query error in browser. Then I wrote this query:
$this->db->where('category_name,publication_status','home_headline_sub',1);
But it still give error. Can anyone help me to solve this? Thanks in advance.
You can chain database clauses, so you would write it as
$this->db->where('category_name','case')->where('publication_status','case')->where('home_headline_sub','case');
This would generate a query's WHERE clause as
// WHERE category_name = 'case' AND publication_status = 'case' AND home_headline_sub = 'case'
Documentation here: http://ellislab.com/codeigniter/user-guide/database/active_record.html#chaining
you to use array in it.
$this->db->where(array('category_name'=>case,'publication_status'=>case,'home_headline_sub'=>case));
but I guess you want to check your value against three columns. you can use
$this->db->or_where(array('category_name'=>1,'publication_status'=>1,'home_headline_sub'=>1));
I hope it will help you.
//The simple way
$this->db->where('foo_field', 'foo_value')
->where('bar_field', 'bar_value')
->where('more_field', 'more_value');
//using custom string
//if your sql is really a complex one you can simply write like these
$this->db->where("(foo_filed = 'foo_value') AND (bar_field = 'bar_value') AND (more_field = 'more_value')");
//or may be with something more complex like this
$this->db->where("(foo_filed = 'foo_value') AND ((bar_field = 'bar_value') OR (more_field = 'more_value'))");
//while using a custom string make sure you put them all in the "double quotation marks" and use no ,commas. It is all a single line. The braces are not necessary always but I like to use them.
Documentation

Codeigniter WHERE AND OR together

I am trying to combine Where And OR in Codeigniter via code.
$this->db->where("id",1);
$this->db->where("status","live")->or_where("status","dead");
Appeared result is as query
where id=1 and status='live' OR status='dead'
Whereas i need result for this query.
where id=1 and (status='live' OR status='dead');
NOTE: Please don't give solution of string passed as parameter from where function. That's not fit into my code. I Just simplified my problem above.
Just found solution, if it can help some one.
$this->db->where("id",1)->where("(status='live' OR status='dead')");
you can use where_in() like this
$status_array = array('live','dead');
$this->db->where("id",1);
$this->db->where_in('status', $status_array);
you just add ->group_start() and ->group_end()
$this->db->where("id",1);
$this->db->where("status","live")
->group_start()
->or_where("status","dead")
->group_end();

How do you work with a single ORM query result in FuelPHP?

I have a query that is returning a single result and I'm wondering if there's a way to access the properties of that result without having to loop through it since I am limiting it to a single result.
Here is my query:
$user = Model_User::find()
->where('email_address', Input::post('email_address'))
->where('password', Input::post('password'))
->limit(1);
The only way I've found to access the results is to run the get() method on $user and loop through the result, but I figured I was missing something and that there was an easier way to return $user as a single object that I can work with since I am limiting it to a single result.
What's the most efficient way to do this?
Did you try
$user->get_one()?
You could also do
$user = Model_User::find_by_email_address_and_password(Input::post('email_address'), Input::post('password'));
Have a nice day :)
Uku Loskit ask you the right syntax.
If you want to retrieve always a single result, you can merge the code:
$user = Model_User::find()
->where('email_address', Input::post('email_address'))
->where('password', Input::post('password'))
->get_one();
An advice for you: be careful using directly Input::post('var_name'), it would be better to use a validation before saving variables.
Another way is to set the framework to perfrom some action, like htmlentities(), for every $_GET and $_POST variable.

Categories