orderby doesn't work in Laravel Eloquent advanced query - sql

I'd like to sort my data by using orderby in Laravel Eloquent advanced query. Here is my code:
$users = User::where(function($query){
$query->orderBy('created_at', 'DESC');
})->get()->toArray();
var_dump($users);
But it doesn't work. Instead if I use orderby like this:
$users = User::orderBy('created_at', 'DESC')->get()->toArray();
var_dump($users);
It works.
Can anybody suggest how to make the orderby works for the advanced query? Thanks

I tried all sorts of different combinations and found the orderBy must be outside the query function (or maybe should be the last one?). Here is the code which is working:
$users = User::where(function($query){
// ......
})->orderBy('created_at', 'DESC')->get()->toArray();
var_dump($users);

Related

Laravel: toSql function not displaying query correctly

I am trying to diedump the query on my index screen using this line of code:
dd(DB::table('members')->where('name', '=', 'Tycho')->toSql());
Now the problem is that when I am displaying the query on my screen I get this:
"select * from `members` where `name` = ?"
My final goal of these lines of code is that I can save offline queries and execute them when the application is online. Unless someone has a solution for this, I'll have to save the queries in a database.
You are seeing the ? placeholders as Laravel uses Prepared Statements.
See Ijas Ameenudeen's answer on another SO question which details how to add a toRawSql() macro on the Eloquent builder which will replace the placeholders with the bindings that you supplied to the original query.
This is because you are using the toSql method, you can use the getBindings method to get the values / bindings.
oneliner:
$query = DB::table('members')->where('name', '=', 'Tycho')->toSql();
// will give the raw query with bindings.
$sqlWithBindings = str_replace_array('?', $query->getBindings(), $query->toSql());
You can try this:
DB::enableQueryLog();
DB::table('members')->where('name', '=', 'Tycho')->get();
echo "<pre>";
print_r(DB::getQueryLog());

How to Fix WHERE Clause in Laravel

I have an issue with Laravel Eloquent when using a WHERE clause.
Code
<?php
$locale = Session::get('locale');
$categories = Category::whereHas('translations', function ($query) use ($locale) {
$query->where('locale', $locale);
})->get();
Generated SQL
select * from `categories`
where exists (select * from `category_translations`
where `category_translations`.`category_id` = `categories`.`id`
and **`locale` = ?**)
It does not register the given value for locale.
I'm also getting the same issue if I put ->where('locale', 'en'), and even if I try a raw query instead of using Eloquent model.
Any help would be much appreciated, thanks.
Like SR_ wrote in the comment toSql() function doesn't return variable binding. If you would like to see how the real queries looks like you can install tools like Laravel Debugar: https://github.com/barryvdh/laravel-debugbar

Query Queried Table Laravel

I was wondering if we could query already queried table. Like this:
$results = Table::where('name','like', '%'.$request['name'].'%')->get();
$results = $results::where('surname', 'like', '%'.$request['surname'.'%'])->get();
I try to do something like this, because I have many options to query from table, and some of them may be empty. So in order not to check all possibilities, and writing different queries, it would be easier in this way. Thanks in advance
The $result variable is in fact a Laravel Collection, so you have a lot of option to work with a Collection including its own where() function.
Imho I will go with this code:
$query = Table::where('name','like', '%'.$request['name'].'%');
$results = $query->get();
$results2 = $query->where('surname', 'like', '%'.$request['surname'.'%'])->get();

Unable to query using 4 conditions with WHERE clause

I am trying to query a database to obtain rows that matches 4 conditions.
The code I'm using is the following:
$result = db_query("SELECT * FROM transportesgeneral WHERE CiudadOrigen LIKE '$origen%' AND DepartamentoOrigen LIKE '$origendep' AND DepartamentoDestino LIKE '$destinodep' AND CiudadDestino LIKE '$destino%'");
But it is not working; Nevertheless, when I try it using only 3 conditions; ie:
$result = db_query("SELECT * FROM transportesgeneral WHERE CiudadOrigen LIKE '$origen%' AND DepartamentoOrigen LIKE '$origendep' AND DepartamentoDestino LIKE '$destinodep'");
It does work. Any idea what I'm doing wrong? Or is it not possible at all?
Thank you so much for your clarification smozgur.
Apparently this was the problem:
I was trying to query the database by using the word that contained a tittle "Petén" so I changed the database info and replaced that word to the same one without the tittle "Peten" and it worked.
Now, im not sure why it does not accept the tittle but that was the problem.
If you have any ideas on how I can use the tittle, I would appreciate that very much.

Order by record count on sub collection

I am trying to convert some old code to use Fluent Nhibernate.
Old code:
allOrders.OrderBy(x => x.OrdersLineItems.Count);
How do I convert it to something like:
query.AddOrder(new Order(????, true));
Is this even possible?
Thanks in advance
UPDATE:
Here is the simplified code I am trying to write:
ICriteria query = FluentSessionManager.GetSession().CreateCriteria<Orders>()
.AddOrder(new Order(????, true));
The joined table is OrdersLineItems. I need to set the order by the count of the line items. Since I am using paging with a data set that has over 500,000 records, simply pulling all the records into memory and then sorting them will not.
Thanks in advance.
ICriteria query = FluentSessionManager.GetSession().CreateCriteria<Orders>()
.CreateAlias("this.OrderLineItems", "oli")
.AddOrder(new Order(Projections.Count("oli.Id"), true));
Something like that I should think. It's probably not perfect but at least illustrates that you need to use Projections.Count to get it done.