I want some help with a WHERE clause $start date is set further up in the code, and the query works when running against SQL from within Laravel. I get an error saying that $startdate isn't set. I am not sure that I am even doing WHERE correctly.
$query = DB::query()
->select('CC AS CountOfVisits', DB::raw('count(CC) AS Users'))
->fromSub
(function (\Illuminate\Database\Query\Builder $query) {
$query->select('user_id', DB::raw('count(user_id) AS CC '))
->from('mytable')
->where('created_at', '>=', $startdate)
->groupBy('user_id');
}, 'CC')
->groupBy('CC');
$result = DB::connection('mysql2')->select($query->toSql());
I'm putting this here for others who find this page. It should be noted that fromSub() can also take a Builder object instead of a closure.
$builder = DB::table('mytable')->where('created_at', '>=', $start_date)
->select('user_id', DB::raw('count(user_id) AS CC '))
->groupBy('user_id');
$query = DB::query()
->select('CC AS CountOfVisits', DB::raw('count(CC) AS Users'))
->fromSub($builder, 'temp')
->groupBy('CC');
In my case, I already had a Builder object that I wanted to use in a sub select.
That's because your fromSub is an anonymous function, also known as a closures. It does not know about variables that you define outside of the closure. You can read more about them in the official PHP docs
Rewrite your query to:
$result = DB::connection('mysql2')
->query()
->select('CC AS CountOfVisits', DB::raw('count(CC) AS Users'))
->fromSub(function($query) use ($startdate) {
$query->select('user_id', DB::raw('count(user_id) AS CC '))
->from('mytable')
->where('created_at','>=',$startdate)
->groupBy('user_id');
}, 'temp')
->groupBy('CC')
->get();
Related
How do I use one query builder to fetch results twice? With Carbon I have use CarbonImmutable to achieve this but with eloquent, one fetch is affecting the others down the line.
Here is the code.
$expenses = PropertyExpense::with(['bill'])
->where('contractor_id', $supplier);
/* I run this to get balance brought forward */
$oldDebits = $expenses->whereDate('txn_date', '<', $start)
->sum('billed'); //here I get actual bbf value.
/* Then I run this to get the debits for the start and end period */
$debits = $expenses
->whereDate('txn_date', '>=', $start)
->whereDate('txn_date', '<=', $end)
->get(); //Here I get empty array. Which should not be the case.
When I remove the $oldDebits Section, I get the Collection of all debits as expected.
I have even rewritten the code to temporarily assign expenses to another variable before executing the sum to no avail. Here.
$olderDebits = $expenses;
$oldDebits = $olderDebits->whereDate('txn_date', '<', $start)->sum('billed');
When I ran this, am still getting the same results: correct $oldDebits and an empty collection for $debits.
Any assistance?
Am using Laravel V9 and PHP 8.1.
That is because you ->whereDate() on to the same variable which is $expenses.
In your case, you should clone the query builder before execute it.
Such as
$expenses = PropertyExpense::with(['bill'])->where('contractor_id', $supplier);
$oldDebits = (clone $expenses)->whereDate('txn_date', '<', $start)->sum('billed');
$debits = (clone $expenses)
->whereDate('txn_date', '>=', $start)
->whereDate('txn_date', '<=', $end)
->get();
I am trying to retrieve data orderby creation date desc and get the first one here is my code
$localnews = Articles::whereHas('sous_categories',
function ($query) {
$query->where('id', '15')->order_by('created_at', 'desc');
})->get()->first();
You must have got error when using order_by as its not the syntax in Laravel.
$localnews = Articles::whereHas('sous_categories',
function ($query) {
$query->where('id', '15')->orderBy('created_at', 'desc');
})->first();
Please have a look at official documentation to help you with.
And when using first() you don't need to use get().
get() we use to fetch multidimensional associative array.
first() we use to fetch one record which matches first.
Here is concise difference between all functions you will use then after. link.
It should be like this,
$localnews=Articles::whereHas('sous_categories', function($query) {
$query->where('id', '15')->orderBy('created_at', 'desc');
})->firstOrFail();
What the best way to use now() with Eloquent? I mean, is there a native Eloquent function to return today's date? I'm using Slim framework and for this query, the only solution that I found is:
$now = date('Y/m/d H:i:s', time());
$articles = Article::where('created_at', '<', $now)
->orderBy('created_at', 'DESC')
->limit(10)
->get();
It's a bit messy, isn't it?
I could use Carbon but it would make an extra dependency...
Thanks
You have two options here: either use DB::raw method to make where method process the given expression as is:
$articles = Article::where(DB::raw('created_at < NOW()'))
->orderBy('created_at', 'DESC')
->limit(10)
->get();
... or use whereRaw method:
$articles = Article::whereRaw('created_at < NOW()')
->orderBy('created_at', 'DESC')
->limit(10)
->get();
As a sidenote, Eloquent has several helper methods for datetime-related processing - whereDate, whereMonth, whereDay, whereYear and whereTime. I'm really not sure those can be used in this specific case, but they might turn helpful elsewhere.
My Requirements : I select baseleads table with Random Order using following conditions
beaseleads currentstatus column value have New Lead Status or
beaseleads currentstatus column value have Call Not Picking status and updated_at date is not Equal to Today Date.
My Laravel Query is below
$baseleadsData=Baseleads::inRandomOrder()->Where('process_status',0)->where(function ($query) {
$query->where('current_status','New Lead');
$query->Orwhere('current_status','Call Not Picking');
$query->OrwhereDate('updated_at', '!=', date('Y-m-d'));
})->first();
Its not Working Properly. What is my Mistake.
->where(function ($query) {
$query->where('current_status','New Lead')
->orWhere('current_status','Call Not Picking')
->orWhere('updated_at', '!=', date('Y-m-d').' 00:00:00');})->first();
It's been a while since I used Laravel, but have you tried
$query->where('current_status', '=', 'New Lead');
$query->Orwhere('current_status', '=', 'Call Not Picking');
instead of
$query->where('current_status','New Lead');
$query->Orwhere('current_status','Call Not Picking');
I'm not sure this will work as it looks like Laravel automatically makes the comparison. What is the error code youre getting? (You can turn debug mode on in your settings file)
you need to use method names in camelCase
use orWhere and orWhereDate
You did mistake of method name, use Orwhere to orWhere, OrwhereDate to orWhereDate and Where to where. and orWhereDate outside of where query.
$baseleadsData=Baseleads::inRandomOrder()
->where('process_status',0)
->where(function ($query) {
$query->where('current_status','New Lead');
$query->orWhere('current_status','Call Not Picking');
})
->orWhereDate('updated_at', '!=', date('Y-m-d'))
->first();
I have a query builder that works:
$article = Page::where('slug', '=', $slug)
->where('hide', '=', $hidden)
->first();
But I want to only add the second where statement if hidden is equal to 1. I've tried the code below which shows the logic of what I'm trying to do, but it doesn't work.
$article = Page::where('slug', '=', $slug);
if ($hidden == 1) {
$article->where('hide', '=', 1);
}
$article->first();
I'm using Laravel 4, but I think the question still stands with Laravel 3.
Yeah there's a little "gotcha" with Eloquent and the query builder. Try the code below ;)
$query = Page::where('slug', '=', $slug);
if ($hidden == 1) {
$query = $query->where('hide', '=', 1);
}
$article = $query->first();
Note the assigning of $query within the conditional. This is becuase the first where (statically called) returns a different object to the query object within the conditional. One way to get around this, I believe due to a recent commit, is like so:
$query = Page::where('slug', '=', $slug)->query();
This will return the query object and you can do what you want as per normal (Instead of re-assigning $query).
Hope that helps.