using pluck on nested results in Laravel - laravel

I have a query that returns the following results.
Illuminate\Database\Eloquent\Collection {#5145
all: [
App\Models\Result {#5207
id: 198,
result_id: 30,
result_type: "App\Models\Touchpoint",
audit_id: 1,
weight: 7,
pics: 0,
recs: 0,
rating: 4,
comments: "none",
complete: 1,
created_at: "2022-06-03 03:42:24",updated_at: "2022-06-03 03:42:24",
result: App\Models\Touchpoint {#5210
id: 30,
name: "Lineman",
description: "The location food offer was available on Lineman",
sort_order: 25,
req_pics: 0,
req_recs: 0,
sector_id: 1,
created_at: null,
updated_at: "2022-04-02 14:02:34",
},
},
App\Models\Result {#5119
id: 199,
result_id: 29,
result_type: "App\Models\Touchpoint",
audit_id: 1,
weight: 7,
pics: 0,
recs: 0,
rating: 4,
comments: "none",
complete: 1,
created_at: "2022-06-03 03:43:38",
updated_at: "2022-06-03 03:43:38",
result: App\Models\Touchpoint {#5206
id: 29,
name: "Grab",
description: "The location food offer was available on Grab",
sort_order: 24,
req_pics: 0,
req_recs: 0,
sector_id: 1,
created_at: null,
updated_at: "2022-04-02 14:02:26",
},
},
],
}
This is the query I'm using to get that collection and I want the result to just contain sort_order, name, description, rating and weight from these results and place them in an array. I'm assuming I need to use pluck to get the correct fields but when I try to pluck 'result.name', etc. I get told result doesn't exist.
$result = Result::query()->where('audit_id', 1)->where('result_type', 'App\Models\Touchpoint')->whereIn('result_id', $tps)->with('result')->get();
This needs to be in a query without manipulating the collection as I need to feed it into Maatwebsite\Excel\Concerns\WithMultipleSheets, which requires a query not the query results.

You can use eager load constraints
$result = Result::query()
->where('audit_id', 1)
->where('result_type', 'App\Models\Touchpoint')
->whereIn('result_id', $tps)
->with('result:id,sort_order,name,description')
->select('id', 'result_id', 'rating', 'weight')
->get();
If you want to remove the nesting and flatten the result set you can map() over the collection
$result->map(function($item) {
$item['sort_order'] = $item->result->sort_order;
$item['name'] = $item->result->name;
$item['description'] = $item->result->description;
//remove the nested relation
$item->unsetRelation('result');
})
->toArray();
/**
* Will return something like
[
[
'id' => 198,
'result_id' => 30,
'rating' => 4,
'weight' => 7,
'sort_order' => 25,
'name' => 'Lineman',
'description' => 'The location food offer was available on Lineman'
],
[
'id' => 199,
'result_id' => 29,
'rating' => 4,
'weight' => 7,
'sort_order' => 24,
'name' => 'Grab',
'description' => 'The location food offer was available on Grab'
]
]
*/
Laravel Docs - Eloquent Relationships - Constraining Eager Loads

Related

Eloquent is sorting my results on its own

I was grouping the orders data for a graph and used the following eloquent query to achieve that,
Order::selectRaw("CONCAT(monthname(created_at),'-',year(created_at)) as date, count(id) as orders")
->groupBy('date')->get();
I got the expected results on my local machine where dates were in normal order, but when running the same thing on production. I get the following output:
Illuminate\Database\Eloquent\Collection {#4607
all: [
App\Order {#4564
date: "April-2020",
orders: 1,
},
App\Order {#4571
date: "August-2019",
orders: 4,
},
App\Order {#4611
date: "December-2019",
orders: 14,
},
App\Order {#4570
date: "February-2020",
orders: 2,
},
App\Order {#4582
date: "January-2020",
orders: 8,
},
App\Order {#4613
date: "June-2020",
orders: 1,
},
App\Order {#4565
date: "March-2020",
orders: 8,
},
App\Order {#4610
date: "May-2020",
orders: 10,
},
App\Order {#4588
date: "November-2019",
orders: 15,
},
App\Order {#4599
date: "October-2019",
orders: 8,
},
App\Order {#4600
date: "September-2019",
orders: 11,
},
],
}
It seems to be sorted in alphabetical order but I cannot figure out why. Can anyone tell me what could be the issue?
And yes on my local I use SQL ver 8, and on prod we use SQL 5, could that be the cause? How would I fix that?
you can order the results output by simply sticking with the raw expression and adding it in the groupBy() as well...
So change this...
->groupBy('date')
To this...
->groupBy(\DB::raw("CONCAT(monthname(created_at),'-',year(created_at)))")
Order::selectRaw("CONCAT(monthname(created_at),'-',year(created_at)) as date, count(id) as orders")
->groupBy(\DB::raw("CONCAT(monthname(created_at),'-',year(created_at)))")->get();
I hope this helps you.
This is what helped me lol...
https://laraveldaily.com/eloquent-trick-group-by-raw-with-boolean-condition/
to get riddle of automatic and non-automatic sort, just sort it your self:
first: go to config\database.php and make mysql non-strict:
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
----------
'strict' => true, // change it to false
then make your query like:
Order::selectRaw("created_at,CONCAT(monthname(created_at),'-',year(created_at)) as date,
count(id) as orders")->orderBy("created_at")
->groupByRaw('date')->get();

How to covert Laravel's collection to array object collection?

I have small laravel collection as below.
[
{
id: 1,
data1: 11,
data2: 12,
data3: 13,
created_at: null,
updated_at: null
},
{
id: 2,
data1: 14,
data2: 15,
data3: 16,
created_at: null,
updated_at: null
}
]
But I would like to convert to array collection like below.
{
data: [
[
11,
12,
13
],
[
14,
15,
16
]
]
}
Appreciated for advice and so sorry for my English. Thank you very much.
Use toArray() which converts this object into an array.
$data->toArray();
Now the collection converted into an array and looks like:-
[
[
id: 1,
data1: 11,
data2: 12,
data3: 13,
created_at: null,
updated_at: null
],
[
id: 2,
data1: 14,
data2: 15,
data3: 16,
created_at: null,
updated_at: null
]
]
But as per your requirements, you don't want associative index for the array, So use
$data = array_values($data);
Now your keys has been removed and final data is:-
[
[
11,
12,
13
],
[
14,
15,
16
]
]

How to return only the child models of a one to many relationship - Laravel

I was hoping I could get some assistance here.
Here is my model structure:
Property 1
--Image 1
--Image 2
Property 2
--Image 3
--Image 4
What I'm trying to do is retrieve all Image models.
This is what I have tried:
$properties = Auth::user()
->landlord_profile_auto
->properties()
->with('images')
->get();
dd($properties->images);
Property [images] does not exist on this collection instance.
Thanks a lot
EDIT:
Here is the dump of a property:
>>> Property::whereHas('images')->with('images')->first()
=> App\Models\Property {#3064
id: 3,
created_at: "2019-01-23 17:31:34",
updated_at: "2019-01-23 20:22:45",
address_line_1: "ABC",
address_line_2: "ABC",
unit: "calculateStorageUsage",
city: "ABC",
postal_code: "calculateStorageUsage",
url_slug: null,
is_draft: 0,
is_refurb: 0,
purchased_date: "2019-01-23",
bedrooms: 3,
max_tenants: null,
rent_amount: "589595.00",
currency_id: 252,
country_id: 491,
rent_frequency_id: 7,
property_type_id: null,
featured_image_id: 4,
landlord_profile_id: 6,
images: Illuminate\Database\Eloquent\Collection {#3059
all: [
App\Models\Image {#3078
id: 4,
created_at: "2019-01-23 20:22:42",
updated_at: "2019-01-23 20:22:42",
name: null,
caption: null,
path: "property_images/Ba1XYIB394xLsH4365391beAZ.jpg",
size_kb: 849.85,
imageable_type: "App\Models\Property",
imageable_id: 3,
},
App\Models\Image {#3077
id: 5,
created_at: "2019-01-23 20:22:45",
updated_at: "2019-01-23 20:22:45",
name: null,
caption: null,
path: "property_images/An3bgmKJzMcPuZyYizp9Lm6dj.jpg",
size_kb: 849.85,
imageable_type: "App\Models\Property",
imageable_id: 3,
},
],
},
}
Properties has a one to many relationship to images. Images is a polymorphic table.
Try this:
#foreach($properties->images as $image)
{
// here you can acess each image
}
#endforeach

How to use collection to merge arrays in laravel so that one becomes the key?

I have an array of arrays like so:
array (
array("Delhi", 22, "The capital of India"),
array("Varanasi", 23, "Oldest Living City"),
array ("Moscow", 24, "Capital of Russia"),
array ("Konya", 25, "The city of Rumi"),
array("Salzburg", 26, "The city of Mozart")
);
I want to make an associated collection like so:
['city' => "Delhi",
'id' => 22,
'description' => "The capital of India"
],
['city' => "Varanasi",
'id' => 23,
'description' => "Oldest Living City"
],
['city' => "Moscow",
'id' => 24,
'description' => "Captial of Russia"
]
This can be done by passing the data through a loop but is there anything in the collection that can get this done?
One could use array_combine or combine from Laravel
$collection = array(
array("Delhi", 22, "The capital of India"),
array("Varanasi", 23, "Oldest Living City"),
array("Moscow", 24, "Capital of Russia"),
array("Konya", 25, "The city of Rumi"),
array("Salzburg", 26, "The city of Mozart")
);
array_map(function($array){
return array_combine(['city', 'id', 'description'], $array);
}, $collection);
//Or with a Laravel collection
collect($collection)->map(function($arr){
return array_combine(['city', 'id', 'description'], $arr);
});

Keying an eager-loaded relationship

I have a Business model and an Hour model. The Business model overrides the protected $with method to eager load it's hours() hasMany relationship.
When I ::first() a given business I receive something like this:
App\Business {#770
id: 5,
user_id: 5,
name: "Wehner-Hudson",
slug: "wehner-hudson",
lat: "55.33593500",
lng: "112.34818600",
created_at: "2018-01-04 13:00:48",
updated_at: "2018-01-04 13:00:48",
hours: Illuminate\Database\Eloquent\Collection {#753
all: [
App\Hour {#802
id: 13,
business_id: 5,
weekday_id: 3,
open: 1,
split_shift: 1,
},
App\Hour {#803
id: 14,
business_id: 5,
weekday_id: 5,
open: 0,
split_shift: 1,
},
App\Hour {#804
id: 15,
business_id: 5,
weekday_id: 2,
open: 1,
split_shift: 0,
},
],
},
},
],
}
I would like to key the hours: Illuminate\Database\Eloquent\Collection {#753 by weekday_id to facilitate processing on the client side. Something like this:
Illuminate\Database\Eloquent\Collection {#763
all: [
1 => App\Hour {#796
id: 1,
business_id: 1,
weekday_id: 1,
open: 1,
split_shift: 1,
},
5 => App\Hour {#767
id: 2,
business_id: 1,
weekday_id: 5,
open: 0,
split_shift: 0,
},
2 => App\Hour {#765
id: 3,
business_id: 1,
weekday_id: 2,
open: 1,
split_shift: 1,
},
],
}
I tried to use keyBy on the relationship in the Business model:
public function hours()
{
return $this->hasMany(Hour::class)->keyBy('weekday_id');
}
But it is not working, as I believe that at that point the returned object is a builder, not a collection.
Try to define an accessor, like this:
public function getHoursByWeekdayAttribute()
{
return $this->hours->keyBy('weekday_id');
}
What about using groupby in your controller.
Business::with(['hours' => function($query){ $query->groupBy('weekend_id'); }])->get();

Resources