Laravel use MAX on join statement - laravel

I'm trying to find how can i use MAX on laravel QueryBuilder or Eloquent join statement, for example:
$userShoppings = \DB::table('shoppings')
->join('products', 'shoppings.product_id', '=', 'products.id')
->select('shoppings.*', 'products.name','products.amount','max(shoppings.ordering_count)')
->where('shoppings.user_ordering_ip', request()->ip())
->get();
in this code i want to get max ordering_count from shoppings table on select method, but i get this error:
Column not found: 1054 Unknown column 'max(shoppings.ordering_count)' in 'field list'
could any body help me to solve this problem?
UPDATE for paste wrong result
Collection {#449 ▼
#items: array:3 [▼
0 => {#446 ▼
+"id": 11
+"product_id": 25
+"user_ordering_ip": "127.0.0.1"
+"ordering_count": 3
+"created_at": "2017-12-25 09:41:01"
+"updated_at": "2017-12-25 09:41:01"
+"amount": "128,440"
+"max(shoppings.ordering_count)": 3
}
1 => {#445 ▼
+"id": 10
+"product_id": 26
+"user_ordering_ip": "127.0.0.1"
+"ordering_count": 1
+"created_at": "2017-12-25 09:32:13"
+"updated_at": "2017-12-25 09:32:13"
+"amount": "137,614"
+"max(shoppings.ordering_count)": 1
}
2 => {#452 ▼
+"id": 9
+"product_id": 49
+"user_ordering_ip": "127.0.0.1"
+"ordering_count": 2
+"created_at": "2017-12-24 17:59:29"
+"updated_at": "2017-12-24 18:35:25"
+"amount": "110,092"
+"max(shoppings.ordering_count)": 2
}
]
}

You could use DB::raw(). So:
$userShoppings = \DB::table('shoppings')
->join('products', 'shoppings.product_id', '=', 'products.id')
->select('shoppings.*', 'products.name','products.amount', DB::raw('max(shoppings.ordering_count)'))
->where('shoppings.user_ordering_ip', request()->ip())
// note: you'll need to also group by all the columns
// you're select in `shoppings.*`
->groupBy('products.name', 'products.amount', 'shoppings.id')
->get();
https://laravel.com/docs/5.5/queries#raw-expressions
For the groupBy() issue you're experiencing, it's possible that you have strict mode enabled for MySQL. You can disable it entirely in your database.php file by setting strict => false under your MySQL connection. However, this will disable all strict checks
If you want to simply disable ONLY_FULL_GROUP_BY, you can add a modes key to your mysql connection in database.php as follows:
modes' => [
'STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
'NO_ZERO_DATE',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_AUTO_CREATE_USER',
'NO_ENGINE_SUBSTITUTION'
]
This will explicitly enable the other checks, but omits ONLY_FULL_GROUP_BY

Related

Add 2 array values in Laravel

I a, new learner and working on home project. I stuck to to get additions of 2 array values . The array values are as follows,
Thanks for your help.. Thanks u
Array 1
array:1 [▼
0 => array:3 [▼
"totalbmilk" => "168.00"
"totala2milk" => "0.00"
"totaljmilk" => "390.00"
]
]
Array 2
array:1 [▼
0 => array:3 [▼
"totalbmilk" => "8.00"
"totala2milk" => "5.50"
"totaljmilk" => "2.50"
]
]
Expecting
totalbmilk = 168 + 8 = 176
totala2milk = 0 + 5.5 = 5.50
totaljmilk = 390 + 2.50 = 392.50
Controller file
$milksalefordairy = Dairymilksale::selectraw('
SUM(buffalomilk) as "totalbmilk",
SUM(a2milk) as "totala2milk",
SUM(jerseymilk) as "totaljmilk"
')
->whereBetween('saledate', [$startdateofmonth, $enddateofmonth])
->get()
->toArray();
$milksaleforcustomer = Customermilksale::selectraw('
SUM(buffalomilk) as "totalbmilk",
SUM(a2milk) as "totala2milk",
SUM(jerseymilk) as "totaljmilk"
')
->whereBetween('saledate', [$startdateofmonth, $enddateofmonth])
->get()
->toArray();
You could use collection methods.
$milksalefordairy = Dairymilksale::selectraw('
SUM(buffalomilk) as "totalbmilk",
SUM(a2milk) as "totala2milk",
SUM(jerseymilk) as "totaljmilk"
')
->whereBetween('saledate', [$startdateofmonth, $enddateofmonth])
->get()
->toArray();
$milksaleforcustomer = Customermilksale::selectraw('
SUM(buffalomilk) as "totalbmilk",
SUM(a2milk) as "totala2milk",
SUM(jerseymilk) as "totaljmilk"
')
->whereBetween('saledate', [$startdateofmonth, $enddateofmonth])
->get()
->toArray();
$collection = collect([...$milksalefordairy, ...$milksaleforcustomer]);
echo $collection->sum('totalbmilk');
echo $collection->sum('totala2milk');
echo $collection->sum('totaljmilk');

Foreach only showing First item in array

I am trying to get data for each id using foreach. But when code run it get only data for 1 ID.. Following is the code
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->get('buffaloID')- >pluck('buffaloID')->toArray();
foreach ($buffalidforavgmilk as $id) {
$milkperid = Buffalomilkrecord::where('buffaloID', $id)->pluck('buffaloID')->toArray();
dd([$buffalidforavgmilk,$milkperid]);
}
Output
array:2 [▼
0 => array:4 [▼
0 => "Buffalo-01"
1 => "Buffalo-02"
2 => "Buffalo-03"
3 => "Buffalo-04"
]
1 => array:5 [▼
0 => "Buffalo-01"
1 => "Buffalo-01"
2 => "Buffalo-01"
3 => "Buffalo-01"
4 => "Buffalo-01"
]
]
Here Loop giving only 1 ID where as required array for all 4 ID
( for Test, i try to get only buffaloID)
Thanks in Advance
dd interrupts execution. If you wanted to dump every result and then stop execution, you should have used dump instead
foreach ($buffalidforavgmilk as $id) {
$milkperid = Buffalomilkrecord::where('buffaloID', $id)->pluck('buffaloID')->toArray();
dump([$buffalidforavgmilk,$milkperid]);
}
dd('Done');
This is not ideal though. You are making a query in each iteration of the loop.
One way you could remove the foreach is to change your query to use whereIn.
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->pluck('buffaloID')->toArray();
$milkperids = Buffalomilkrecord::whereIn('buffaloID', $buffalidforavgmilk)->pluck('buffaloID')->toArray();

how to save array data coming from view in laravel

This the data when user submit the form :
POST Data
_token
"JNDt8WC6kVbvrSdFTKSGnHsfzTuIsbthslf5Gqjs"
invoice_number
"15"
dateofbill
"2019-04-19"
customer_name
"praveen kumar tiwari"
customer_mobile
"8924001750"
sno
array:3 [▼
0 => "1"
1 => "2"
2 => "3"
]
item_name
array:3 [▼
0 => "jeans"
1 => "shirt"
2 => "lower"
]
qty
array:3 [▼
0 => "2"
1 => "3"
2 => "2"
]
price
array:3 [▼
0 => "20000"
1 => "232"
2 => "12"
]
gst
array:3 [▼
0 => "1200"
1 => "22"
2 => "12"
]
discount
array:3 [▼
0 => "100"
1 => "23"
2 => "12"
]
textarea
""
i cannot be able to store this data into a table. i am trying with for loop but getting an error "Undefined offset: 3".
Code inside the controller
for($i=0;$i<=count($request['sno']);$i++)
{
$invoice = new Invoice;
$invoice->sendbill_id=$bill->id;
$invoice->sno=$request['sno'][$i];
$invoice->item_name=$request->item_name[$i];
$invoice->qty=$request->qty[$i];
$invoice->price=$request->price[$i];
$invoice->gst=$request->gst[$i];
$invoice->discount=$request->discount[$i];
$invoice->save();
}
i want to store these 3 values comming in the array form (sno,item_name,qty,price,gst,discount) in 3 diffrent rows
You should try to use laravel eloquent to save it. Here is some example that you can check it out. Laravel : Many to many insertion
The problem you have is indeed your loop: for($i=0;$i<=count($request['sno']);$i++).
To be specific it is this right here <=:
$i<=count()
^^
Take a look at your array:
[
0 => "1"
1 => "2"
2 => "3"
]
You got a total of 3 objects. count($request['sno']) will therefore return 3 since the count() function does not start counting at 0!
However, calling an index (e.g. $request['sno'][1]) will not return the first object (0 => "1") but the second (1 => "2"). I think you see where I am going.
Since the loop will go on until $i equals 3 the loop will be completed 4 times. At the last time (where $i == 3) you try to get the 4th item out of your array which does not exist so an error message pops up: Undefined offset: 3.
To solve this just change this
$i<=count()
^^
to <. The loop will only be executed if $i is still smaller then 3. This is the case if $i == 2. No error message will pop up.
I do not want to attack or hurt you in any way, but it seems to me that you are relatively new to PHP. Of course, that's not a shame, but I'm wondering if a huge framework like Laravel is right for you. First the basics, then comes the advanced.
But that's only as a small comment and tip from me.

Laravel 5.4 whereNotIn apparently not working

I have logic in a controller that builds an array called $exclude.
Using dd for $exclude I get :
array:4 [▼
0 => 2
1 => 3
2 => 4
3 => 5
]
which is correct.
I want to exclude those from a result so I have:
$potype = DB::table('potypes')
->whereNotIn('id',[$exclude])
->get();
but when I run the query those items are included with the exception of the first in the array. So I enabled the query log with
DB::enableQueryLog();
and ran
dd(DB::getQueryLog());
with the result of
array:1 [▼
0 => array:3 [▼
"query" => "select * from `potypes` where `id` not in (?)"
"bindings" => array:4 [▼
0 => 2
1 => 3
2 => 4
3 => 5
]
"time" => 0.67
]
]
The table has 8 records but running the query is returning 7, only ommiting the first of the list:
Collection {#621 ▼
#items: array:7 [▼
If I use implode
$ex = implode(',',$exclude)
and change the query to
->whereNotIn('id',[$ex])
I get the same result - 7 items with just the first in the list being ignored.
Is this an Eloquent bug or me?
delete [ ] and check it again:
$potype = DB::table('potypes')
->whereNotIn('id',$exclude)
->get();
OK it was realtively simple with Mohammed's comment pointing me in the right direction.
As $exclude was an array I changed the get to:
$potype = DB::table('potypes')
->whereNotIn('id',$exclude)
->get();
and it worked OK!

Laravel Many to Many sync with null

I'm trying to use sync function like that:
$round->competitors()->sync($fighters);
$fighter is :
Collection {#339 ▼
#items: array:3 [▼
0 => 5
1 => null
2 => 6
]
}
When it get to the null element, I get :
QueryException in Connection.php line 647:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '' for column 'competitor_id' at row 1 (SQL: insert into `round_competitor` (`competitor_id`, `round_id`) values (, 29))
I get the same result if I try:
$round->competitors()->sync([null, null]);
But if I try:
$round->competitors()->attach(null);
it works without any problem???
Why is that happening???
Call filter() on your $fighters so that the null values are removed.
$round->competitors()->sync($fighters->filter());
If you do: $round->competitors()->attach(null); is it the same as if you just don't make any attach? That's probably why it is working!!

Resources