1

I have table attribute_values(id, value, attr_group_id).
I need to return the collection grouped by key attr_group_id.

in clear php using ORM RedBean i made:

$data = \DB::table('attribute_values')->get();
$attrs = [];
foreach ($data as $k => $v){
    $attrs [$v['attr_group_id']][$k] = $v['value'];
   }
return $attrs;

I need same using Laravel, after this one:

  $data = \DB::table('attribute_values')->get();

My table

  id    value     attr_group_id
   1     one          1
   2     two          1
   3     three        2
   4     four         2
   5     five         3
   6     six          3

And i need result

   Array(
[1] => Array 
    (
    [1] => one
    [2] => two
    )
[2] => Array 
    (
    [3] => three
    [4] => four
    )
[3] => Array 
    (
    [5] => five
    [6] => six
    )
  )
6
  • sorry, my pictures. my table : prntscr.com/o18o89 and i need result: prntscr.com/o18oxp Commented Jun 13, 2019 at 8:11
  • try $data = \DB::table('attribute_values')->groupBy('attr_group_id')->get(); Commented Jun 13, 2019 at 8:15
  • do you have Model For this if yes share the Model Name Commented Jun 13, 2019 at 8:21
  • no i havent. I do not want to create a separate model for this. Commented Jun 13, 2019 at 8:34
  • @ Sohel0415 it wont work because you are grouping the record in mysql query so the first record from each attr_group_id will be returened and rest of them will be skipped Commented Jun 13, 2019 at 9:37

5 Answers 5

7

Fetch all data, and map it with attribute id of every row will work,

$data = \DB::table('attribute_values')->get();
$attrs = [];
foreach ($data as $key => $value) {
    // -> as it return std object
    $attrs[$value->attr_group_id][] = $value->value;
}
dd($attrs);
Sign up to request clarification or add additional context in comments.

9 Comments

Please check my question. I made adjustments and added what I need: My table and need result.
try answer by @Martin Henriksen
since laravel has a collection so you don't need foreach
@Drakula Predator Larevel Version please
Ok if we will group by attr_group_id it won't give two results for the same attr_group_id but OP's result has two records per each attr_group_id. So @Martin Henriksen's data will fetch only three records and will skip remaining from each attr_group_id.
|
3

You can use the groupBy() function of collection as:

$data = \DB::table('attribute_values')->get()->groupBy('attr_group_id');

It merges records with same attr_group_id under this field's value as making key of the collection.

2 Comments

Please check my question. I made adjustments and added what I need: My table and need result.
@SashaSan - This function creates a collection making attr_group_id attribute as a collection key. If you want to convert it into an array you can also use toArray() function of collection.
3

Doing all this in raw SQL will be more efficient, SQL database are quite good at these operations. SQL has a group by function, since you are overwriting value, i just get it out with max() (this seems weird, that you overwrite the value, do you actually just want unique results?).

DB::table('attribute_values')
    ->select('attr_group_id', DB::raw('max(value)'))
    ->groupBy('attr_group_id')
    ->get();

EDIT Since the scope has changed, you can utilize Laravels Collection methods, that is opreations on a Collection.

DB::table('attribute_values')
    ->get()
    ->groupBy('attr_group_id')
    ->toArray();

3 Comments

Please check my question. I made adjustments and added what I need: My table and need result.
its the elegant way using colletion
Please check my answer. it is described below. I made it for you. explained what the task was and how it was solved.
2

Friends, this is a ready task that I needed ! I did it myself and you helped me. If anyone interested can read.

I'll explain to you why I needed this particular method. I am doing an online store with a clock and now there was a task to make filters and attributes for filters. So there are three tables

attribute_groups table

enter image description here

attribute_products table

enter image description here

attribute_values

enter image description here

I need to display the Laravel widget on my .blade.php like as

{{ Widget::run('filter', 'tpl' => 'widgets.filter', 'filter' => null,]) }} 

When i creating a new product in the admin panel. I must to save the product id and attribute_id in attribute_products, but there can be as many attributes as possible for one product. so, if I'll use this option

$data = \DB::table('attribute_values')
            ->get()
            ->groupBy('attr_group_id')
            ->toArray(); 

I got result:

enter image description here

But! each new array starts with index 0. But I need an index that means its id. attr_group_id from table attribute_value for saving into attribute_products. And after I see only one method for me.

$data = \DB::table('attribute_values')->get();
        $attrs = [];
        foreach ($data as $key => $value) {
            $attrs[$value->attr_group_id][$value->id] = $value->value;
        }

        return $attrs;

and the result I was looking for

enter image description here

now you can see what's the difference and what was needed. Array index starts 1,2,3,4,5 and this index = attr_group_id. Unfortunately I could not initially ask the right question. thanks to all.

2 Comments

can you share the sql file wih some data. i will dig deeper into it and fulfill your requirement
bro ) I have already did what I needed .. I share my completed task.
1

Laravel Version 5.8

So You need to Group the id if You need in the Model Way I have created the Model as AttributeValue

$modelWay = \App\AttributeValue::get()
            ->groupBy('attr_group_id');

if You need in the DBWay I have created the table as attribute_values

$dbWay = \DB::table('attribute_values')
        ->get()
        ->groupBy('attr_group_id');

Both Will give the Same Result

1 Comment

Please check my answer. it is described below. I made it for you. explained what the task was and how it was solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.