How do I flatten a collection with hierarchy self referenced models, tree collections into a single dimension collection. I have a self referencing model having parents and children.
I want the result to return a eloquent collection, not a simple collection or an array. array has been used as result results for easy demonstration
relationships are declared like this.
public function parent()
{
return $this->belongsTo(self::class, 'parent_id');
}
public function parentRecursive()
{
return $this->parent()->with('parentRecursive');
}
public function children()
{
return $this->hasMany(self::class, 'parent_id');
}
public function childrenRecursive()
{
return $this->children()->with('childrenRecursive');
}
so when i call the model->childrenRecursive it returns the collection as it should be. like this. i have changed it toArray() to make it easy to read.
array:1 [
0 => array:6 [
"id" => 5
"name" => "I am a child of 1"
"parent_id" => "1"
"created_at" => "2016-12-26 13:53:50"
"updated_at" => "2016-12-26 13:53:50"
"children_recursive" => array:1 [
0 => array:6 [
"id" => 6
"name" => "I am child of 5"
"parent_id" => "5"
"created_at" => "2016-12-26 13:53:50"
"updated_at" => "2016-12-26 13:53:50"
"children_recursive" => array:2 [
0 => array:6 [
"id" => 7
"name" => "I am child of 6"
"parent_id" => "6"
"created_at" => "2016-12-26 13:53:50"
"updated_at" => "2016-12-26 13:53:50"
"children_recursive" => []
],
1 => array:6 [
"id" => 8
"name" => "I am child of 6 too"
"parent_id" => "6"
"created_at" => "2016-12-26 13:53:50"
"updated_at" => "2016-12-26 13:53:50"
"children_recursive" => []
]
]
]
]
]
]
what I want to achieve is the collection to be single dimension. here is how the toArray() to that collection should look like.
array:4 [
0 => array:6 [
"id" => 5
"name" => "I am a child of 1"
"parent_id" => "1"
"created_at" => "2016-12-26 13:53:50"
"updated_at" => "2016-12-26 13:53:50"
],
1 => array:6 [
"id" => 6
"name" => "I am child of 5"
"parent_id" => "5"
"created_at" => "2016-12-26 13:53:50"
"updated_at" => "2016-12-26 13:53:50"
],
2 => array:6 [
"id" => 7
"name" => "I am child of 6"
"parent_id" => "6"
"created_at" => "2016-12-26 13:53:50"
"updated_at" => "2016-12-26 13:53:50"
],
3 => array:6 [
"id" => 8
"name" => "I am child of 6 too"
"parent_id" => "6"
"created_at" => "2016-12-26 13:53:50"
"updated_at" => "2016-12-26 13:53:50"
]
]
I have tried many collection methods like filter, flatMap, flatten and multiple array methods. but haven't found an appropriate solution.
It's a bit late, but I'm going to post what I wish I had been able to find before I ended up writing it myself.
Similar to the original post, I have a recursive parent/child relationship in my categories table (but this could apply to any table with a self-referencing parent_id column). You can set up your Model like this:
Category.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model {
// Relationships
public function parent()
{
return $this->belongsTo('App\Models\Category', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Models\Category', 'parent_id');
}
public function nested_ancestors()
{
return $this->belongsTo('App\Models\Category', 'parent_id')->with('parent');
}
public function nested_descendants()
{
return $this->hasMany('App\Models\Category', 'parent_id')->with('children');
}
// Attributes
public function getFlatAncestorsAttribute()
{
return collect(flat_ancestors($this));
}
public function getFlatDescendantsAttribute()
{
return collect(flat_descendants($this));
}
}
Then somewhere in your application, you need to have a place to put some global helper functions. You could follow the instructions found here, and then just paste in the following helper functions:
Helpers.php
function flat_ancestors($model) {
$result = [];
if ($model->parent) {
$result[] = $model->parent;
$result = array_merge($result, flat_ancestors($model->parent));
}
return $result;
}
function flat_descendants($model) {
$result = [];
foreach ($model->children as $child) {
$result[] = $child;
if ($child->children) {
$result = array_merge($result, flat_descendants($child));
}
}
return $result;
}
The code above will then allow you to use $category->flat_ancestors, which will produce a flat collection of all the category's ancestors, no matter how many there are. Similarly, using $category->flat_descendants will yield a flat collection of all the child categories, and the child's children categories, and so on until all the posterity categories have been accounted for.
Some things to be careful of:
This type of approach could potentially lead to an infinite loop if
you have Category 1 referencing Category 2 as its parent, and
then Category 2 has Category 1 as its parent. Just be careful
that parent/child relationships are incest free :-)
This type of approach also isn't very efficient. It'll be fine for a bunch of
parent/child recursive relationships, but especially for the
flat_descendants functions, the number of database queries grows
exponentially for each generation level.
I didn't find any builtin method into theLaravel collection either. You may try something like this (Use it as a global function or as a dedicated class method, it's up to you. here is the idea):
function flatten($array) {
$result = [];
foreach ($array as $item) {
if (is_array($item)) {
$result[] = array_filter($item, function($array) {
return ! is_array($array);
});
$result = array_merge($result, flatten($item));
}
}
return array_filter($result);
}
Then use it like this:
// When available into global scope as a function
$flattenArray = flatten($arrayFromTheCollection);
This will will recursively flatten. It doesn't prevent duplicates though, so you'll need to filter them out if that's an issue.
In your AppServiceProvider::boot method
use Illuminate\Support\Collection;
//...
Collection::macro('flattenTree', function ($childrenField) {
$result = collect();
foreach ($this->items as $item) {
$result->push($item);
if ($item->$childrenField instanceof Collection) {
$result = $result->merge($item->$childrenField->flattenTree($childrenField));
}
}
return $result;
});
Then
$flattened = $myCollection->flattenTree('childrenRecursive');
// or in the case of the question
$flattened = $model->childrenRecursive->flattenTree('childrenRecursive');
this is my code, it might help ^_^
Collection::macro('flattenTree', function ($childrenField = 'children', $levelAttribute = 'level')
{
$toProcess = $this->items;
$processed = [];
while($item = array_shift($toProcess))
{
$item->$levelAttribute ++;
$processed[] = $item;
if (count($item->$childrenField) > 0) {
$children = array_reverse($item->$childrenField->items);
foreach ($children as $child) {
$child->$levelAttribute = $item->$levelAttribute;
array_unshift($toProcess,$child);
}
}
}
return Collection::make($processed);
});
you should put this code in the boot method of AppServiceProvider.php or any provider you wish, and then you can use it like this
Category::where('parent_category_id', null)->get()->flattenTree();
this will flat the tree and add a level attribute to each object to indicate the depth level of the object
good luck for everyone
For these who does run into a dead loop because of incest relationship, I used this solution to retrieve descendants' attributes through eager loaded relationship - worked like fully flattening the relationship but avoid running into dead loop by foreach.
Solution link
Related
I don't know why I can't figure this out.
In my controller, how can I loop through this array and only get the values for name and url.
both of those values will be passed to insert a new record.
array:3 [▼
0 => array:2 [▼
"name" => "Discogs"
"url" => "https://www.discogs.com/artist/267549"
]
1 => "2"
2 => array:2 [▼
"name" => "Official homepage"
"url" => "http://www.blackmetal.com/~mega/TBD/"
]
]
You can do with this code:
foreach ($array as $value) {
if (is_array($value) && isset($value['name']) && isset($value['url'])) {
// Do whatever you want
}
}
You can try utilising Laravel's collection for this...
$items = collect($array)
->filter(function($item) {
return is_array($item);
});
If you have extra attributes to the ones you listed then you can use map() to for this:
$items = collect($array)
->filter(function($item) {
return is_array($item);
})
->map(function($item) {
return Arr::only($item, [
'name',
'url',
];
});
p.s. don't forget to add use Illuminate\Support\Arr; to use Arr
I have 1 table name page_live. Now I want to display it if isMenu = 1. Now it is connected to it self with filed name parent_Id.
As an example -
I have page_live named test_page and this row is a parent of a row named inside-1. And inside-1 is parent of inside-2.
Now, I have to create array which will look like -
[0]=>{
'name' => 'test_page'
[0]=> {
'name' => 'inside-1'
[0] => {
'name' => 'inside-2'
}
}
}
This is my table -
Model PageLive
<?php
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
class PageLive extends Model
{
protected $table = 'page_live';
protected $fillable = ['name', 'adminId', 'slugName', 'description',
'imageId', 'metaTitle', 'metaDesc', 'metaKeyword', 'pageTypeId', 'parent_id',
'isHome', 'pageDraftId', 'themeLayoutId'];
public function parent()
{
return $this->belongsTo(App\Http\Models\PageLive::class, 'parent_id');
}
public function children()
{
return $this->hasMany(App\Http\Models\PageLive::class, 'parent_id');
}
}
Please help me.
Thank you.
You Need to use recursive relations in your Model:
public function childrenPages()
{
return $this->hasMany(PageLive::class, 'parent_id', 'id');
}
public function allChildrenPages()
{
return $this->childrenPages()->with('allChildrenPages');
}
Then in Controller:
$page = PageLive::with('allChildrenPages')->first();
$page->allChildrenPages; // collection of recursively loaded children
// each of them having the same collection of children:
$page->allChildrenPages->first()->allChildrenPages; // .. and so on
I can't guarantee it will be efficient for your data, I tried to give you the idea and part of the code, you need to test it definitely.
You can use recursive function to achieve this.
public function abc( $ar, $pid = null ) {
$op = array();
foreach( $ar as $item ) {
if( $item['parent_id'] == $pid ) {
$op[$item['id']] = $item;
// using recursion
$children = $this->abc( $ar, $item['id'] );
if( $children ) {
$op[$item['id']]['children'] = $children;
}
}
}
return $op;
}
Use function something like this and call it wherever you want.
You will get array structure like -
array:1 [▼
1 => array:5 [▼
"id" => 1
"name" => "Test Page"
"slugName" => "test-page"
"parent_id" => null
"children" => array:1 [▼
3 => array:5 [▼
"id" => 3
"name" => "Inside 1"
"slugName" => "test-page2"
"parent_id" => "1"
"children" => array:1 [▼
4 => array:4 [▼
"id" => 4
"name" => "Inside 2"
"slugName" => "test-page3"
"parent_id" => "3"
]
]
]
]
]
]
Hope this will help you.
I'm trying to create a collection of Attributes using model bindings and group the attributes into sets before outputting as a resource. I have my relationships set as follows:
Variant Model App\Variant
public function attributes()
{
return $this->belongsToMany(Attribute::class, 'variant_attributes')
->withPivot('value');
}
Attributes Model App\Attribute
public function variants()
{
return $this->belongsToMany(Variant::class, 'variant_attributes');
}
public function set()
{
return $this->belongsTo(AttributeSet::class, 'attribute_set_id');
}
Attribute Sets Model App\AttributeSet
public function attributes()
{
return $this->hasMany(Attribute::class);
}
Ideal Output
Illuminate\Database\Eloquent\Collection {#718 ▼
#items: array:2 [▼
"essentials" => array:2 [▼
"name" => "Essentials"
"attributes" => array:2 [▼
"repellendus" => array:2 [▼
"name" => "repellendus"
"value" => "1"
]
"incidunt" => array:2 [▶]
]
]
"interior" => array:2 [▶]
]
}
Essentials and Interior are the Attribute Sets and their associated attributes are the children with the key of attributes. The pivot value comes from the variant_attributes table. I am also binding the Product and Variant to a controller...
Now, this is what I have done, however it doesn't feel right whatsoever calling $variant = $attribute->variants->first(); on a belongsToMany in this instance. I also feel this is overcomplicated.
$attributeSets = AttributeSet::with(['attributes.variants' => fn($query) => $query->withPivot('value')->where('id', $variant->id)])
->whereHas('attributes.variants', fn($query) => $query->where('id', $variant->id))
->get();
$attributeSets = $attributeSets->mapWithKeys(function ($attributeSet) {
$attributes = $attributeSet['attributes']->filter(function ($attribute) {
return $attribute->variants->count();
})->mapWithKeys(function ($attribute) {
$variant = $attribute->variants->first();
return [
$attribute['identifier'] => [
'name' => $attribute['name'],
'value' => $variant['pivot']['value']
]
];
})->toArray();
return [
$attributeSet['identifier'] => [
'name' => $attributeSet['name'],
'attributes' => $attributes
]
];
});
Thanks in advance!
The probleme is that when dd($responsablle or $type) its shows only first_name
i need to select first_name and id
public function create(){
$responsable = User::all()->pluck('first_name','id');
$type = EventType::all()->pluck('type','id');
return view ('backend.event.create', compact('responsable', 'type'));
}
First use pluck on the Builder instead of retrieving all the records with all their fields then plucking the fields from the Collection:
$responsable = User::pluck('first_name', 'id');
$type = EventType::pluck('type', 'id');
The second arguement is the field you want to key the Collection/array by. The id part is the key of the element:
foreach ($responsable as $key => $value) {
// $key is the 'id' field
// $value is the 'first_name'
}
foreach ($type as $key => $value) {
// $key is the 'id' field
// $value is the 'type'
}
Or to be more useful with the naming:
foreach ($responsable as $id => $first_name) { ... }
foreach ($type as $id => $type) { ... }
Laravel 5.8 Docs - Query Builder - Retrieving Results - Retrieving A List Of Column Values pluck
Laravel 5.8 Docs - Collections - Available Methods - pluck pluck
To be honest, you don't actually have to use pluck() here. If you simply limit the columns being returned via ->select(), you will receive records with their attributes limited to the columns specified:
$users = User::select('first_name', 'id')->get();
$types = EventType::select('type', 'id')->get();
Now, when looping over these, you'll have access to first_name, id and type, id:
foreach($users AS $user){
echo $user->id."|".$user->first_name;
}
foreach($types AS $type){
echo $type->type."|".$type->id;
}
Note, this does return the full Model for User and EventType, but casting to an array will condense that to just an associative array for each record:
$users = User::select('first_name', 'id')->get()->toArray();
dd($users);
/* array:2 [▼
0 => array:2 [▼
"first_name" => "Bob"
"id" => "1"
]
1 => array:2 [▼
"first_name" => "Mike"
"id" => "2"
]
] */
$types = EventType::select('type', 'id')->get()->toArray();
dd($types);
/* array:2 [▼
0 => array:2 [▼
"type" => "Red"
"id" => "1"
]
1 => array:2 [▼
"type" => "Blue"
"id" => "2"
]
] */
Then, when looping, you can access similarly:
foreach($users AS $user){
echo $user["id"]."|".$user["first_name"];
}
// Or, $users[0]["first_name"], etc.
foreach($types AS $type){
echo $type["type"]."|".$type["id"];
}
// Or, $types[0]["type"], etc.
I have 3 tables tests, questions, options.
As you can imagine
a test has many questions
a question belongs to a test
a question has many options
an option belongs to a question
These relations are set up in the models already.
I got the data from the front end in this form:
array:3 [
"name" => "First Test"
"preparation" => "First Test prep"
"questions" => array:2 [
0 => array:2 [
"title" => "Some question"
"options" => array:4 [
0 => "a"
1 => "b"
2 => "c"
3 => "d"
]
]
1 => array:2 [
"title" => "Another question"
"options" => array:4 [
0 => "e"
1 => "f"
2 => "g"
3 => "h"
]
]
]
]
This data perfectly represents these relationships. In fact if I were using a NoSql database I would simply store this in the database.
My question is "what is the best way to store all of this data at once while using eloquent in Laravel"?
Note: It is in the form of Laravel's collection.
class Test extends Model {
$table = 'tests';
function questions(){
return $this->hasMany(Question::class, 'test_id');
}
}
class Question extends Model {
$table = 'questions';
function answers(){
return $this->hasMany(Answer::class, 'question_id');
}
function test(){
return $this->belongsTo(Test::class, 'test_id');
}
}
class Answer extends Model {
$table = 'answers';
function question(){
return $this->belongsTo(Question::class, 'question_id');
}
}
of course i showed only relations ,tables and foreign keys.
you can add any additional data to your models.
You have to create a structure of model objects from given data.
JMS Serializer is a great library to do that, and it has laravel integration.