I am trying to select records from my MSSQL database, with below parameters:
Column 'first_etd' must be between two dates
Column 'car_id' must not be the same as the current $carId variable.
This is my code:
$carId = 47;
$from = Carbon::now()->subWeeks(2)->startOfWeek()->toDateString();
$to = Carbon::now()->addWeeks(4)->endOfWeek()->toDateString();
$consols = Consol::with(['car'])
->where('car_id', '!=', $carId)
->whereBetween('first_etd', [$from, $to])->get();
The above variable $consols returns no results.
If I remove the ->where('car_id', '!=', $carId) from the statement, I successfully get results.
All the records in my database currently have NULL in the car_id column:
I have also tried to change the != operator to <> without any luck.
So this is not a fix to the SQL statement itself, but more a fix to my problem.
As said in my OP, I can find the two records if I remove the where() method. I figured I could start by getting the records, that's between my two dates and then do the where() filtering on the result collection.
This works:
//Get the records from the database, that's between two dates.
$consols = Consol::with(['car'])->whereBetween('first_etd', [$from, $to])->get();
//Now $consols is a Laravel collection, so I can use the where() method here.
$consols = $this->consols->where('car_id', '!=', $carId);
Above successfully returns the two records.
Related
I want to compare two values of the database. Is it possible to do so with the "where" method? For example, the "tnx_time" would be one DB value and the "value(duration)" the other one. But I cannot now access the DB values on the 3rd field of the "where" function.
Does anybody know how to fix that?
$trnxs = Transaction::where('tnx_time', '<', date("Y-m-d", strtotime( value(duration) )) )
You can use a callback in your "where" clause to create a subquery, would be something like this (might need some changing)
$trnxs = Transaction::where('tnx_time', '<', function ($query) {
$query->selectRaw('date("Y-m-d", strtotime(value(duration)))');
})->get();
I want to use count and sum together on DB Query not sure how to go about it. I've tried several combinations but keep getting an error. I know I can just use a raw query but would like to learn how to use it correctly
Working:
DB::select('SELECT count(*) AS order_count, sum(total_including_vat)
AS orders_total FROM orders WHERE user_id =' .$userProfile->id);
Not Working
DB::table('orders')->where('user_id', '=', $userProfile->id)->count()->Sum();
count same as aggregates returns single value so
// you try to call method sum on number and it fails
DB::table('orders')->where('user_id', $userProfile->id)->count()->sum();
you can make two requests to get sum and count but its not a good idea, or get data in collection and let it do the math
// not a good idea
//$count = DB::table('orders')->where('user_id', $userProfile->id)->count();
//$sum = DB::table('orders')->where('user_id', $userProfile->id)->sum('total_including_vat');
//collection way
$orders = DB::table('orders')
->where('user_id',$userPorfile->id)
->get(['id', 'total_including_vat']);
$result = [
'order_count' => $orders->count(),
'orders_total' => $orders->sum('total_including_vat')
];
or the same result as for your working example with mix raw expressions
$result = DB::table('orders')
->where('user_id', $userProfile->id)
->selectRaw('count(1) as order_count, sum(total_including_vat) as orders_total')
->first();
is there any possibility to retrieve records as a range.For an example there is a table with column as ref_numbers.Sample values for the ref_numbers are A1,A2,A3,A4....AB1,AB2,AB3,AB4...
I want to retrieve the records of specific range starting value and end value.Such as in this case (A1-A2,AB1-AB4)
How can i achieve this ,Using eloquent or query builder or Raw queries in laravel?
You can use this where between operator.
$data = DB::table('table_name')
->whereBetween('ref_numbers', ['A1', 'A10'])
->get();
or
$data = DB::table('table_name')
->where('ref_numbers', '>', 'A1')
->where('ref_numbers', '<', 'A10')
->get();
You can read here more https://laravel.com/docs/9.x/queries#additional-where-clauses
i want to get difference between two values. i get my last entered value in bill no and get difference with input value.
this is my controller function model
$restPaymentSales = DB::table('sales')
->select('rest_payment')
->where('bill_no', $request->input('bill_no'))
->orderBy('created_at', 'desc')
->first();
$payment = $request->input('payment');
$doubleVal = doubleval($payment);
and i wrote calculation like this
$restSales = $restPaymentSales->child['rest_payment'] - $doubleVal;
but it shows me this error
Trying to get property of non-object
my table row like this
rest_payment -> double(11,2)
how can i fix this issue. basically i want to get difference between table last value order by date and input value.
Update your calculation from:
$restSales = $restPaymentSales->child['rest_payment'] - $doubleVal;
TO
$restSales = $restPaymentSales->rest_payment - $doubleVal;
I have a table called gk and I am currently running two queries. Please have a look at the queries:
Gk::groupBy(DB::raw("MONTH(created_at)"))
->groupBy(DB::raw("YEAR(created_at)"))
->selectRaw('id, user_id, sum(ton) as ton,pl, count(id) as total, sum(w) , created_at')
->with(array('user'=> function($q){
$q->select('id', 'userName', 'profilePic');
}))
->where('user_id', $userData[0]->id)
->get();
This query returns a little summary of every months. As you can I see I am grouping results by months and years. And I have another query which will return all the rows of any given months.
I am running second query like this
$m=Carbon::parse($request->date);
Gk::where('user_id',$request->user_id)->whereRaw(DB::raw("YEAR(created_at)=$m->year"))->whereRaw(DB::raw("MONTH(created_at)=$m->month"))
->orderBy('created_at','desc')
->get();
The second query returns all the rows of any month. I'm executing this query in a foreach loop for all of the months that are returned in the first query.
I am trying to combine this two query into one so that I can get a group of the results by months and years and also all the details of that month.
Any help, suggestions or idea would be extremely helpful.
[Note: For the date in second query, this date is created_at result from the first query.]
Thank you.
The way I read your question is as following: The second query is executed in a loop with results from the first one. Is that right? In my answer I have explained a way to execute the second query just one time instead of in a loop. You'd still have to execute the first query once.
So, I think that you are better of using the Php collection methods:
$results = Gk::where('user_id',$request->user_id)
->orderBy('created_at','desc')
->get()
->groupBy(function (Gk $item) {
return $item->created_at->format('Y-m');
});
The groupBy method has to return an attribute on which you want to group the elements. For this example I think that using a yyyy-mm format will do fine.
Reference: https://laravel.com/docs/5.5/collections#method-groupby
Edit: Maybe you can also get rid of the orderBy method call because you are grouping by afterwards:
$results = Gk::where('user_id',$request->user_id)
->get()
->groupBy(function (Gk $item) {
return $item->created_at->format('Y-m');
});
Edit 2: To combine the information of the two queries, you could do something like the following:
$results = Gk::where('user_id',$request->user_id)
->get()
->groupBy(function (Gk $item) {
return $item->created_at->format('Y-m');
})->map(function(Collection $rows) {
return [
'sum(ton)' => $rows->sum('ton'),
'total' => $rows->count(),
'sum(w)' => $rows->sum('w'),
'rows' => $rows
];
);
Note that I have omitted a few of the selected columns in your first query because they are not unique in the given group by. But feel free to add any logic in the map function. Because we use map() after groupBy, every call of map() will receive a collection of items for one month. You can that use that fabulous collection magic to calculate all values that you need and reduce the number of queries to just one.