id
agent_id
currency
1
A0001
IDR
2
A0002
MYR
3
A0001
THB
example currently have a dataset as above,
is it have any way to using only 1 query builder to get the outcome like below
Output:
[
"agent_id" => "A0001",
"currency" => [
"IDR",
"THB",
],
],
[
"agent_id" => "A0002"
"currency" => ["MYR"]
]
Basically likes try to pluck the currency under same agent
Appreciate for all the suggestion.
Found a solution for this problem
$output = $output
->get()
->groupby('agent_id')
->map(function($rows){
return [
"agent_id" => $rows[0]['agent_id'],
"currency" => $rows->pluck('currency'),
];
});
Related
I have a request data like this.
array:6 [
"teacherid" => "1"
"classid" => "7"
"schedule" => array:5 [
0 => "Monday - lesson 1"
1 => "Monday - lesson 2"
2 => "Monday - lesson 3"
3 => "Wednesday - lesson 3"
4 => "Wednesday - lesson 4"
]
"year" => "2021"
"smt" => "1"
"_token" => "tSFppSS2TWPQYbQofJD6pPufTLFNpKWAssZNGIHO"
]
and DB look like this
table schedules
I want to validate the input teacher, schedule and classroom like this:
if schedule, teacher and classroom are duplicate
or if schedule and teacher duplicate, but different classroom
I've tried with rule::unique as below but validation doesn't work.
how to make validation of point 1 and 2 above with rule::unique ?
$messages = ['schedule.*.unique' => 'Schedule :input already taken'];
$validator = \Validator::make(
$request->all(),
[
'schedule.*' => 'required',
Rule::unique('schedules')->where(function ($query) use ($request) {
return $query->where('schedule', $request->schedule);
->where('teacher_classes_id', $request->classid)
->where('teacher_subjects_id', $request->teasubid);
}),
],
$messages
);
Query to get monthly orders (total orders per month(count) or total sales per month(sum)):
Tried this query, but it is not working. Also tried with other results from StackOverflow, but I didn't understand how it is done with MongoDB query. This is the link to that question : select-sum-column-and-group-by-with-mongodb-and-laravel
$monthly_orders = Order::select(
DB::raw('sum(total_amount) as sum'),
DB::raw('YEAR(created_at) year, MONTH(created_at) month'),
)
->groupBy('month')
->get();
When I try to get total amount by using group by customer ID , it is returning sum as null
$monthly_orders = Order::selectRaw('sum(total_amount) as sum, customer_id')
->groupBy('customer_id')
->pluck('sum', 'customer_id');
Result :
Illuminate\Support\Collection {#2123 ▼
#items: array:4 [▼
"6098e5ff5977a25ee96a2a42" => null
"60dbf87f7d8ffb7cdb2233d2" => null
"605af409195d8e59e34893f2" => null
"60ddae4a66fb69678e45f056" => null
]
}
Try using raw and aggregate
$monthly_orders = Order::raw(function ($collection) {
return $collection->aggregate([
[
'$group' => [
"_id" => '$customer_id',
'customer_id' => ['$first' => '$customer_id'],
'sum' => ['$sum' => '$total_amount']
]
],
]);
});
you can use pluck
$monthly_orders->pluck('sum','customer_id')
Group by month
$monthly_orders = Order::raw(function ($collection) {
return $collection->aggregate([
[
'$group' => [
"_id" => ['$month'=>'$created_at'],
'customer_id' => ['$first' => '$customer_id'],
'sum' => ['$sum' => '$total_amount']
]
],
]);
});
I need to pluck two columns name and score from my table corporate_objectives and put it in my graph chart. I'm having two different behavior and I can't seem to get my desired result.
1st code
$getNameAndScore = CorporateObjective::pluck('name');
foreach($getNameAndScore as $key => $item) {
$corporateObjective[] = [$item, '('.$key.'%)'];
}
Result:
"xAxis": [
[
"PEOPLE DEVELOPMENT",
"(0%)"
],
[
"OPTIMUM SYSTEMS AND PROCESSES",
"(1%)"
],
[
"CUSTOMER MANAGEMENT",
"(2%)"
],
[
"REVENUE GROWTH",
"(3%)"
]
],
2nd code
$getNameAndScore = CorporateObjective::pluck('name', 'score');
foreach($getNameAndScore as $key => $item) {
$corporateObjective[] = [$item, '('.$key.'%)'];
}
Result:
"xAxis": [
[
"REVENUE GROWTH",
"(25%)"
]
],
I'm getting all the correct name but the incorrect score in my first code. On my second code, I'm getting the correct name and score but all data is not being pulled out. I wanted to achieve the first code with all the correct score from the second code.
EDIT:
This is how my database looks like
id | name | score
1 PEOPLE DEVELOPMENT 25
2 OPTIMUM SYSTEMS AND PROCESSES 25
3 CUSTOMER MANAGEMENT 25
4 REVENUE GROWTH 25
Is there another way other than pluck? It seems like pluck merges / filters all data with the same value.
This is the correct output of your code. There is no problem here
$getNameAndScore = CorporateObjective::pluck('name', 'score');
foreach($getNameAndScore as $key => $item) {
$corporateObjective[] = [$item, '('.$key.'%)'];
}
How does work pluck here is description
If duplicate keys exist, the last matching element will be inserted into the plucked collection:
$collection = collect([
['brand' => 'Tesla', 'color' => 'red'],
['brand' => 'Pagani', 'color' => 'white'],
['brand' => 'Tesla', 'color' => 'black'],
['brand' => 'Pagani', 'color' => 'orange'],
]);
$plucked = $collection->pluck('color', 'brand');
$plucked->all();
// ['Tesla' => 'black', 'Pagani' => 'orange']
Details in here
So I just made an alternative way of doing it and it might help other people. If there is a more proper way or cleaner way of doing it, please feel free to correct my answer.
$getNameAndScore = CorporateObjective::pluck('name');
foreach($getNameAndScore as $item) {
$key = CorporateObjective::where('name', $item)->value('score');
$corporateObjective[] = [$item, '('.$key.'%)'];
}
return response()->json([
'xAxis' => $corporateObjective,
]);
Result
"xAxis": [
[
"PEOPLE DEVELOPMENT",
"(25%)"
],
[
"OPTIMUM SYSTEMS AND PROCESSES",
"(1%)" // I changed the value in the database and it works
],
[
"CUSTOMER MANAGEMENT",
"(22%)" // I changed the value in the database and it works
],
[
"REVENUE GROWTH",
"(25%)"
]
],
I have an array from query like below:
array:84 [
0 => array:2 [
"comp" => "50007148"
"cus" => "F0401"
]
1 => array:2 [
"comp" => "50007148"
"cus" => "J0050"
]
2 => array:2 [
"comp" => "50007148"
"cus" => "L"
]
3 => array:2 [
"comp" => "50007148"
"cus" => "LT"
]
4 => array:2 [
"comp" => "50007148"
"cus" => "RP"
]
Now I need to write a query where comp, cus in above query.
$rslt = Stdetl::whereIn('comp, cus', $categories)
->where(YEAR(docdate), '=', 2019)
->get(SUM(number))->toArray();
But this query is not working. I am getting error as follows:
(1/1) FatalErrorException
Call to undefined function App\Http\Controllers\YEAR()
But this is not the only mistake in that query .
YEAR() is a mysql function, you should use whereRaw() to query this. Like this:
->whereRaw('YEAR(docdate) = 2019')
Update:
For your whereIn() part, you have to make two queries, one for each column. So you will have to get the correct values from the array. This can be done using array_map.
For example:
->whereIn('comp', array_map(function($cat) { return $cat['comp']; }, $categories))
->whereIn('cus', array_map(function($cat) { return $cat['cus']; }, $categories))
You can't use whereIn like that, use this way
$rslt=Stdetl::whereIn('comp', $categories)
->whereIn('cus', $categories)
->where(date('Y', strtotime(docdate)), '=', 2019)
->get(SUM(number))->toArray();;
I have a retrieved restaurant list. when the restaurant menu is empty that restaurant showed in last order.. what i do.. can you help..
My Query is :
$restaurantList = $this->Restaurants->find('all', [
'conditions' => $conditions,
'contain' => [
'DeliveryLocations' => [
'conditions' => $areaLocationConditions,
],
'RestaurantMenus' => [
'conditions' => [
'RestaurantMenus.status' => 1,
'RestaurantMenus.delete_status' => 'N'
]
]
],
'limit' => 5,
'order' => 'Restaurants.id DESC'
])->hydrate(false)->toArray();
Simple solution:
by implementing CounterCache
https://book.cakephp.org/3.0/en/orm/behaviors/counter-cache.html and order by cache results.
More complex:
by using Case statements
https://book.cakephp.org/3.0/en/orm/query-builder.html#case-statements
select 'has_menus' if restuarant has menus then 1 else 0
order by that results